LintCode 798: Backpack VII (DP 经典题)

  1. Backpack VII
    中文English
    Assume that you have n yuan. There are many kinds of rice in the supermarket. Each kind of rice is bagged and must be purchased in the whole bag. Given the weight, price and quantity of each type of rice, find the maximum weight of rice that you can purchase.

Example
Example 1:

Input: n = 8, prices = [3,2], weights = [300,160], amounts = [1,6]
Output: 640
Explanation: Buy the second rice(price = 2) use all 8 money.
Example 2:

Input: n = 8, prices = [2,4], weight = [100,100], amounts = [4,2 ]
Output: 400
Explanation: Buy the first rice(price = 2) use all 8 money.

解法1:

class Solution {
public:
    /**
     * @param n: the money of you
     * @param prices: the price of rice[i]
     * @param weight: the weight of rice[i]
     * @param amounts: the amount of rice[i] 
     * @return: the maximum weight
     */
    int backPackVII(int n, vector<int> &prices, vector<int> &weight, vector<int> &amounts) {
        int itemCount = prices.size();   //count of items
        vector<vector<int>> dp(itemCount + 1, vector<int>(n + 1, 0)); //dp[i][j] means the maximum weight of first i tems with total price <= j
        
        for (int i = 1; i <= itemCount; ++i) { 
            for (int k = 1; k <=n; ++k) {
                dp[i][k] = dp[i - 1][k];
            }

            for (int j = 0; j <= amounts[i - 1]; ++j) {
                for (int k = 1; k <= n; ++k) { //k->  1 .. n
                    if (k >= j * prices[i - 1]) {
                        dp[i][k] = max(dp[i][k], dp[i - 1][k - j * prices[i - 1]] + j * weight[i - 1]);
                    }
                }
            }
        }

        return dp[itemCount][n];
    }
};

解法2:
代码如下:

class Solution {
public:
    /**
     * @param n: the money of you
     * @param prices: the price of rice[i]
     * @param weight: the weight of rice[i]
     * @param amounts: the amount of rice[i]
     * @return: the maximum weight
     */
    int backPackVII(int n, vector<int> &prices, vector<int> &weight, vector<int> &amounts) {
        int itemCount = prices.size();
        vector<int> dp(n + 1, 0);
        
        for (int i = 1; i <= itemCount; ++i) {
            for (int j = 1; j <= amounts[i - 1]; ++j) {
                for (int k = n; k >= prices[i - 1]; --k) {
                    dp[k] = max(dp[k], dp[k - prices[i - 1]] + weight[i - 1]);
                }
            }
        }
            
        return dp[n];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值