Description
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.
Solution
这题与Backpack IV唯一的区别就是不能重复放置,因此只要将第二个循环改成从大到小反向遍历即可。
public class Solution {
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
public int backPackIV(int[] nums, int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for (int i = 0; i < nums.length; i++) {
for (int j = target; j >= nums[i]; j--) {
dp[j] += dp[j-nums[i]];
}
}
return dp[target];
}
}