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.
一刷
题解:用传统的backtrack会出现超时,由于题目暗示用dynamic programming, 容易联想到转移方程为:
f(target) = f(target - nums[0]) + f(target - nums[1]) + ... + f(target - nums.back())
public class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target+1];
dp[0] = 1;
for(int i=1; i<=target; i++){
for(int num:nums){
if(i>=num) dp[i]+=dp[i-num];
}
}
return dp[target];
}
}
二刷
dynamic programming
class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new [target+1];
dp[0] = 1;
for(int i=1; i<=target; i++){
for(int num : nums){
if(i>=num) dp[i] += dp[i-num];
}
}
return dp[target];
}
}
共有4个combination sum:
Combination Sum
Combination Sum II
Combination Sum III
Combination Sum IV