- 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是求解的值。
注意:
- j循环必须是从大到小。
- 因为这里是求有有多少种解,所以用
dp[j] += dp[j - nums[i]];
而backpack I是求解的值,即最多能装多少
dp[k] = max(dp[k], dp[k - A[i]] + A[i]); - 此题为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];
}
};