Question 1 : Rob-Cutting
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces.
vector<int> price = {1,5,8,9,10,17,17,20,24,30};
Input: 3
Output: 8
Input: 4
Output: 10
Solution 1: Dynamic Programming (recursive version - Top to Bottom)
int help(const vector<int> price,int n,vector<int> res){
if(res[n] >= 0){
return res[n];
}
if(n == 0){
return 0;
}
int cut = INT_MIN;
for(int i = 1; i <=n; i++){
cut = max(cut,price[i - 1] + help(price,(n - i),res));
}
res[n] = cut;
return cut;
}
int robcut(const vector<int> price,int n){
vector<int> res;
for(int i = 0; i <= n; i++){
res.push_back(-1);
}
return help(price,n, res);
}
Explanation: Every can seperate the problem by computing every possible cutting position. In the 'help' function, the 'for' loop is to cut from the first position to n position. Using 'res' to prevent repetitive computation.
Note: Pay attention to the index of 'price' and 'help' in the loop.
Solution 2: Dynamic Programming (normal version - Bottom to Top)
int robcut2(const vector<int> price, int n){
vector<int> res;
int i;
for(i = 0; i <= n; i++){
res.push_back(INT_MIN);
}
res[0] = 0;
for(i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
res[i] = max(res[i],price[j - 1] + res[i - j]);
}
}
return res[n];
}
Explanation: Compute the smaller question first and store the result in 'res'. When big problem use it, just take it from the 'res'.
Similar Question : Leetcode 241. Different Ways to Add Parentheses (Solution is in "Divide and Conquer").
本文探讨了杆切割问题的两种动态规划解决方案,一种是从顶部到底部的递归版本,另一种是从底部到顶部的标准版本。通过计算所有可能的切割位置来确定由长度为n的杆切割并出售零件所能获得的最大价值。

306

被折叠的 条评论
为什么被折叠?



