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

本文深入探讨了完全背包问题,对比01背包,讲解了其核心算法及转移方程,并提供了两种解题方法,包括二维数组解法和空间优化后的解法,通过实例解释了完全背包与01背包的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Backpack X

You have a total of n yuan. Merchant has three merchandises and their prices are 150 yuan, 250 yuan and 350 yuan. And the number of these merchandises can be considered as infinite. After the purchase of goods need to be the remaining money to the businessman as a tip, finding the minimum tip for the merchant.

Example
Example 1:

Input: n = 900
Output: 0
Example 2:

Input: n = 800
Output: 0

经典的完全背包例题。
解法1:最朴素的2维数组
注意:

  1. 完全背包和01背包的区别就是转移方程里面,
    f[i][w] = max{f[i-1][w], f[i-1][w-Ai-1] + Vi-1 | w≥Ai-1 且f[i-1][w-Ai-1] ≠-1} //01背包
    f[i][w] = max{f[i-1][w], f[i][w-Ai-1] + Vi-1} //完全背包
    i-1和i的区别。
    注意,完全背包这里的转移方程本来应该是f[i][w] = max_k{f[i-1][w-kAi-1] + kVi-1},这里k>=0表示w里面最多能去取多少Ai-1。
    那为什么该方程等价于
    f[i][w] = max{f[i-1][w], f[i][w-Ai-1] + Vi-1}
    呢?
    我们举个例子,假如Ai-1=2, Vi-1=V
    f[i][10]=max{f[i-1][10]+0V, f[i-1][8]+1V, f[i-1][6]+2V, f[i-1][4]+3V, f[i-1][2]+4V, f[i-1][0]+5V}

    f[i][8]=max{f[i-1][8]+0V, f[i-1][6]+2V, f[i-1][4]+3V, f[i-1][5]+4V}
    可得
    f[i][10]=max{f[i-1][10], f[i][8]+V}
    即f[i][w] = max{f[i-1][w], f[i][w-Ai-1]+V}

  2. 完全背包和01背包都只需要2重循环,优化也只是空间优化而已。
    多重背包需要3重循环(不管优不优化),优化也只是空间优化。

  3. j=0和j=1开始都可以。

  4. i和j两层循环顺序可互换。

class Solution {
public:
    /**
     * @param n: the money you have
     * @return: the minimum money you have to give
     */
    int backPackX(int n) {
        vector<int> prices={150, 250, 350};
        vector<vector<int>> dp(4, vector<int>(n + 1));
        
        for (int i = 1; i <= 3; ++i) {
            for (int j = 0; j <= n; ++j) {   //j=1 也可以
                dp[i][j] = dp[i - 1][j];
                if (j >= prices[i - 1]) {   //note it is >=
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - prices[i - 1]] + prices[i - 1]);
                }
            }
        }
        
        return n - dp[3][n];
    }
};

解法2:
空间优化后2层循环,一重数组。
注意:

  1. 01背包空间优化内循环反序,完全背包空间优化内循环正序。
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];
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值