欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LintCode 801: Backpack X (完全背包类型题,DP)

程序员文章站 2022-07-05 12:58:22
...

经典的完全背包例题。
优化后2层循环,一重数组。

class Solution {
public:
    /**
     * @param n: the money you have
     * @return: the minimum money you have to give
     */
    int backPackX(int n) {
        
        vector<int> dp(n + 1, 0); 
        //dp[x] means the maximum amount (that is less than x) used to buy the mechandises
        vector<int> prices = {150, 250, 350};
        
        for (int i = 0; i < 3; ++i) {
            for (int j = prices[i]; j <= n; ++j) {
                dp[j] = max(dp[j], dp[j - prices[i]] + prices[i]);        
            }
        }
        
        return n - dp[n];
    }
};
相关标签: LintCode