LeetCode Combination Sum IV

LeetCode 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.

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 {
private:
void dfs(vector<int>& nums, int sum, int& ans) {
if (sum == 0) {
++ans;
return;
}
if (sum < 0)return;
for (const auto &i : nums) {
if (sum >= i) {
dfs(nums, sum - i, ans);
}
}
}
public:
int combinationSum4(vector<int>& nums, int target) {
int ans = 0;
dfs(nums, target, ans);
return ans;
}
};

class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1, 0);
dp[0] = 1;
for (int i = 0; i < nums.size(); ++i) { // 对每个数字
for (int j = target; j >= nums[i]; --j) {
dp[j] += dp[j - nums[i]]; // 取值；不取dp[j]保持不变；所以取和不取加起来就是+=dp[j-nums[i]]
}
}
return dp[target];
}
};

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; ++i) {
for (int j = 0; j < nums.size(); ++j) {
if (i >= nums[j])dp[i] += dp[i - nums[j]];
}
}
return dp[target];
}
};