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:用dfs去找出所有的路径,然后如果等于target,+1,但是超时,这题必须用dp来解决。
public class Solution {
/**
* @param nums: an integer array and all positive numbers
* @param target: An integer
* @return: An integer
*/
public int backPackV(int[] nums, int target) {
if(nums == null || nums.length == 0) return 0;
int[] res = new int[1];
Arrays.sort(nums);
dfs(nums, target, res, 0, 0);
return res[0];
}
private void dfs(int[] nums, int target, int[] res, int start, int curSum) {
if(start > nums.length || curSum > target) {
return;
}
if(curSum == target) {
res[0] += 1;
return;
}
for(int i = start; i < nums.length; i++) {
curSum += nums[i];
dfs(nums, target, res, i+1, curSum);
curSum -= nums[i];
}
}
}
思路2:dp[i][j] 表示,第i个数,cursum为j的情况下,有多少种表达方式;
public class Solution {
/**
* @param nums: an integer array and all positive numbers
* @param target: An integer
* @return: An integer
*/
public int backPackV(int[] nums, int target) {
if(nums == null || nums.length == 0) return -1;
int n = nums.length;
int[][] dp = new int[n+1][target+1];
// initial;
dp[0][0] = 1;
for(int i=1; i<dp.length; i++) {
for(int j=0; j<dp[0].length; j++) {
// calculate matrix;
// 默认的dp[i][j] ,就是不取nums[i];
dp[i][j] = dp[i-1][j];
// 如果说取,加上取的可能性个数;
if(i-1 >= 0 && j-nums[i-1] >=0) {
dp[i][j] += dp[i-1][j-nums[i-1]];
}
}
}
return dp[n][target];
}
}