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.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1, 0);
dp[0] = 1;
for(int i = 1; i < target + 1; i++){
for(int n : nums){
if(n <= i)
dp[i] += dp[i - n];
}
}
return dp[target];
}
};

本文探讨了给定正整数数组求和至目标值的所有可能组合数量问题,并提供了一个C++实现示例。通过动态规划的方法,实现了高效计算。此外,还讨论了允许负数的情况及其对问题的影响。
259

被折叠的 条评论
为什么被折叠?



