题目
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
答案
Backpack题是要找出最大不超过target的物品重量sum
Backpack V题是要找出有多少种物品重量sum刚好等于target
而这个Backpack VI题是要找出有多少种物品重量sum刚好等于target,每个物品可以无限用,而且只要用的顺序不一样就算一种组合
dfs+memorization
class Solution {
int[] dp = null;
public int combinationSum4(int[] nums, int target) {
if(target == 0) return 1;
int ans = 0;
dp = new int[target + 1];
Arrays.fill(dp, -1);
dp[0] = 1;
recur(nums, target);
return dp[target];
}
public int recur(int[] nums, int target) {
// if(target == 0) return 1; This line is not needed if you have initilized dp[0] = 1
if(dp[target] != -1) return dp[target];
int ans = 0;
for(int i = 0; i < nums.length; i++) {
if(target >= nums[i]) {
ans += recur(nums, target - nums[i]);
}
}
dp[target] = ans;
return ans;
}
}
dp
public class Solution {
/**
* @param nums: an integer array and all positive numbers, no duplicates
* @param target: An integer
* @return: An integer
*/
public int backPackVI(int[] nums, int target) {
int n = nums.length, m = target;
if(n == 0) return 0;
int[] f = new int[target + 1];
f[0] = 1;
for(int i = 1; i <= m; i++) {
for(int j = 0; j < n; j++) {
if(i - nums[j] >= 0)
f[i] = f[i] + f[i - nums[j]];
}
}
return f[m];
}
}
网友评论