Dynamic Programming

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").

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值