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.

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?

如果given array有正有負的數字,那麼答案會變得無限多種組合。譬如given array = [-1, 0, 1],然後target是0,這樣[0], [1, -1], [1, -1, 1, -1]都符合,長度可以無限增加只要正負數都一直放入組合裡。

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();
}
int combinationSum4(vector<int>& nums, int target) { // time: O(n * target); space: O(target)
    vector<int> memo(target + 1, -1);
    memo[0] = 1;
    return helper(nums, target, memo);
}
int helper(vector<int>& nums, int target, vector<int>& memo) {
    if (memo[target] != -1) return memo[target];
    int res = 0;
    for (int i = 0; i < nums.size(); ++i) {
        if (target >= nums[i]) {
            res += helper(nums, target - nums[i], memo);
        }
    }
    return memo[target] = res;
}

Last updated

Was this helpful?