377. Combination Sum IV
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.int combinationSum4(vector<int>& nums, int target) { // time: O(n * target); space: O(target)
if (target == 0) return 1;
sort(nums.begin(), nums.end());
vector<double> dp(target + 1, 0);
dp[0] = 1;
int n = nums.size();
for (int i = 1; i <= target; ++i) {
for (int j = 0; j < n; ++j) {
if (nums[j] > i) break;
dp[i] += dp[i - nums[j]];
}
}
return dp.back();
}Last updated