LintCode 563: Backpack V(经典01背包问题)

  1. Backpack V
    中文English
    Given n items with size nums[i] which an integer array and all positive numbers. An integer target denotes the size of a backpack. Find the number of possible fill the backpack.

Each item may only be used once

Example
Given candidate items [1,2,3,3,7] and target 7,

A solution set is:
[7]
[1, 3, 3]
return 2

解法1:
经典01背包问题的变种。跟Backpack I不同的是这里是求有多少种解,而backpack是求解的值。
注意:

  1. j循环必须是从大到小。
  2. 因为这里是求有有多少种解,所以用
    dp[j] += dp[j - nums[i]];
    而backpack I是求解的值,即最多能装多少
    dp[k] = max(dp[k], dp[k - A[i]] + A[i]);
  3. 此题为01背包,所以第2层循环为从大到小。
    附网上评论:
    无重复背包即01背包,得到的结果dp[i]是根据之前的结果来的,换句话说,是否选入当前物品是根据之前没有当前物品的子结果而做出的选择,是为了保证每一个物品的唯一性。
    有重复背包即完全背包,每个物品都有无限的可重复性,所以当前的结果要从之前已经出现过当前物品的子结果中得到。
    所以循环的方向要反一下,一个从下到上,一个从上到下。
class Solution {
public:
    /**
     * @param nums: an integer array and all positive numbers
     * @param target: An integer
     * @return: An integer
     */
    int backPackV(vector<int> &nums, int target) {
        int n = nums.size();
        vector<int> dp(target + 1, 0);  //dp[i] is the number of possible fill i
        dp[0] = 1;
        for (int i = 0; i < n; ++i) {
            for (int j = target; j >= nums[i]; j--) {
                dp[j] += dp[j - nums[i]];
            }
        }
        return dp[target];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值