[LeetCode] Minimum Cost to Cut a Stick

1547. Minimum Cost to Cut a Stick

Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:

Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.

You should perform the cuts in order, you can change the order of the cuts as you wish.

The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.

Return the minimum total cost of the cuts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int dp[103][103];
int helper(vector<int>& cuts, int l, int r) {
if(l + 1 >= r) return 0;
if(dp[l][r] != -1) return dp[l][r];
dp[l][r] = INT_MAX;
for(int i = l + 1; i < r; i++) {
dp[l][r] = min(dp[l][r], cuts[r] - cuts[l] + helper(cuts,l,i) + helper(cuts,i,r));
}
return dp[l][r];
}
public:
int minCost(int n, vector<int>& cuts) {
cuts.push_back(0);
cuts.push_back(n);
memset(dp,-1,sizeof(dp));
sort(cuts.begin(), cuts.end());
return helper(cuts, 0, cuts.size() - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/03/PS/LeetCode/minimum-cost-to-cut-a-stick/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.