377. Combination Sum IV
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.
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int>dp(target+1,0);
for(int i=1;i<=target;i++){
for(int j=0;j<nums.size();j++){
if(i==nums[j]){
dp[i]++;
}
else if(i>nums[j]){
dp[i]+=dp[i-nums[j]];
}
}
}
return dp[target];
}
};
简析:
dp[i]表示到达i的路径条数。
如数组[1,2,3]
dp[4]=dp[4-1]+dp[4-2]+dp[4-3];
表示到达4的路径条数 = 到达3的路径条数(dp[4-1])+到达2的路径条数(dp[4-2])+到达1的路径条数(dp[4-3])状态方程:
1、i>nums[j]时
dp[i]=dp[i-nums[0]]+dp[i-nums[1]]+dp[i-nums[2]]+......dp[i-nums[j]]+...
2、i==nums[j]时
dp[i]=dp[i]+1;//如数组[1,2,3]---->当j=2,即nums[2]=3时,dp[3]=dp[3]+1,从3到3只有一条路径,所以加1即可!