杆子分割

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36346463/article/details/81062849

给一个 n 英寸长的杆子和一个包含所有小于 n 的尺寸的价格. 确定通过切割杆并销售碎片可获得的最大值.例如,如果棒的长度为8,并且不同长度部件的值如下,则最大可获得值为 22(通过切割两段长度 2 和 6 )

您在真实的面试中是否遇到过这个题?  

样例

长度    | 1   2   3   4   5   6   7   8  
--------------------------------------------
价格    | 1   5   8   9  10  17  17  20

给出 price = [1, 5, 8, 9, 10, 17, 17, 20], n = 8 返回 22//切成长度为 2 和 6 的两段

长度    | 1   2   3   4   5   6   7   8  
--------------------------------------------
价格    | 3   5   8   9  10  17  17  20

给出 price = [3, 5, 8, 9, 10, 17, 17, 20], n = 8 返回 24//切成长度为 1 的 8 段


two solution: 1 er wei qujian DP; 2 duplicate backpack

class Solution {
public:
    /*
     * @param : the prices
     * @param : the length of rod
     * @return: the max value
     */
    int cutting(vector<int>& prices, int n) {
        // Write your code here
        if (prices.size() != n) {
            return 0;
        }
        if (n == 1) {
            return prices[0];
        }
        vector<int> cut_maxs(n + 1, 0);
        // init
        cut_maxs[1] = prices[0];
        for (int i = 2; i <= n; i++) {
            int max_cut = prices[i - 1];// no cut
            for (int j = 1; j <= i/2; j++) {
                max_cut = max(cut_maxs[j] + cut_maxs[i - j], max_cut);
            }
            cut_maxs[i] = max_cut;
        }
        return cut_maxs[n];
    }
    
};

class Solution {
public:
    /**
     * @param prices: the prices
     * @param n: the length of rod
     * @return: the max value
     */
    int cutting(vector<int> &prices, int n) {
        // Write your code here
        if (prices.size() != n || n == 0) {
            return 0;
        }
        vector<int> dp(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (j >= i) {
                    dp[j] = max(prices[i - 1] + dp[j - i], dp[j]);
                }
            }
        }
        return dp[n];
    }
};



猜你喜欢

转载自blog.csdn.net/weixin_36346463/article/details/81062849