Tuesday, October 8, 2019

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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

============= Recursive ============ .    (Time limit exceed)

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        int ans = 0;
        helper(nums, 0, target, ans);
        return ans;
    }
    
    void helper(vector<int>& nums, int sum, int target, int& ans) {
        if (sum == target) {
            ans++;
        }
        if (sum >= target) {
            return;
        }
        
        for (int num : nums) {
            sum += num;
            helper(nums, sum, target, ans);
            sum -= num;
        }
        return;
    }
};


============= DP   (similar to climbing stairs problem =========


class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target + 1);
        dp[0] = 1;
        for (int i = 1; i <= target; ++i) {
            for (auto a : nums) {
                if (i >= a) dp[i] += dp[i - a];
            }
        }
        return dp.back();
    }
};


or

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target + 1);
        dp[0] = 1;
        sort(nums.begin(), nums.end());
        for (int i = 1; i <= target; ++i) {
            for (auto a : nums) {
                if (i < a) break;
                dp[i] += dp[i - a];
            }
        }
        return dp.back();
    }
};


or  ================ Efficient recursive ==============

 class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        unordered_map<int, int> memo;
        return helper(nums, target, memo);
    }
    int helper(vector<int>& nums, int target, unordered_map<int, int>& memo) {
        if (target < 0) return 0;
        if (target == 0) return 1;
        if (memo.count(target)) return memo[target];
        int res = 0, n = nums.size();
        for (int i = 0; i < n; ++i) {
            res += helper(nums, target - nums[i], memo);
        }
        return memo[target] = res;
    }
};
 

No comments:

Post a Comment