leetcode:801 · 背包问题X

题目描述

在这里插入图片描述

class Solution {
public:
    /**
     * @param n: the money you have
     * @return: the minimum money you have to give
     */
    int backPackX(int n) {
        // write your code here
    }
};

题目解析

完全背包

思路和lintcode:440 背包问题 III一样

  • 定义: dp[i][j]表示用i件物品,j元情况下最多能有多少价值
  • dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - prices[i]] + prices[i]) 当前物品不取VS取
class Solution {
public:
    /**
     * @param n: the money you have
     * @return: the minimum money you have to give
     */
    int backPackX(int n) {
        std::vector<int> prices  = {150, 250, 350};
       
        std::vector<std::vector<int>> dp(4, std::vector<int>(n + 1));
        for (int i = 1; i <= 3; ++i) {
            int price = prices[i - 1];
            for (int j = 1; j <= n; ++j) {
                if(j >= price){
                    dp[i][j] = std::max(
                            dp[i - 1][j],
                            dp[i - 1][j - price] + price
                            );
                }else{
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return  n  - dp[3][n];
    }
};
  • 定义 dp[j]:手上有 j 元,最多能花出去多少;
class Solution {
public:
    int backPackX(int n) {
        std::vector<int> prices  = {150, 250, 350};
        std::vector<int> dp(n + 1);
        dp[0] = 0;
        int len = prices.size();
        for (int i = 1; i <= len; ++i) {
            int price = prices[i - 1];
            for (int j = price; j <= n; ++j) {
                dp[j] = std::max(dp[j], dp[j - price]  + price );
            }
        }
        return n - dp[n];
    }
};
  • 定义 dp[j]:手上有 j 元,买东西后最少剩余多少(剩余的钱给小费);

  • 思路:尽量将钱都用来买东西 => 背包尽量装满
  • 状态:dp[i]表示是否能花费j元
  • 转移方程:dp[i] = dp[i - 150] || dp[i - 250] || dp[i - 350]
  • 初始条件:dp[0] = true
  • 答案:n - i for the first dp[i] is true, i = n ... 150

  • 数学
class Solution {
public:
    int backPackX(int n) {
        // write your code here
        if (n < 150) return n;
        if (n < 250) return n-150;
        if (n < 300) return n-250;
        if (n < 350) return n-300;
        return n%50;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值