yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #377. Combination Sum IV #288

Open yokostan opened 5 years ago

yokostan commented 5 years ago

The 'intuitive' solution:

class Solution {
    public int combinationSum4(int[] nums, int target) {
        if (nums == null || nums.length == 0) return 0;
        if (target == 0) return 1;
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            if (target >= nums[i]) {
                sum += combinationSum4(nums, target - nums[i]);
            }
        }
        return sum;
    }
}

But will get TLE in leetcode.

If we use dp to store how many combinations we can get for each target number, then our runtime can beat 100%:

class Solution {
    public int[] dp;
    public int combinationSum4(int[] nums, int target) {
        if (nums == null || nums.length == 0) return 0;
        dp = new int[target + 1];
        Arrays.fill(dp, -1);
        dp[0] = 1;
        return helper(nums, target);
    }

    public int helper(int[] nums, int target) {
        if (dp[target] != -1) return dp[target];
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            if (target >= nums[i]) {
                res += helper(nums, target - nums[i]);
            }
        }
        dp[target] = res;
        return res;
    }
}
yokostan commented 5 years ago

Bottom-up DP:

class Solution {
    public int combinationSum4(int[] nums, int target) {
        int[] dp = new int [target + 1];
        dp[0] = 1;
        int n = nums.length;
        for (int i = 1; i <= target; i++) {
            for (int j = 0; j < n; j++) {
                if (i - nums[j] >= 0) {
                    dp[i] = dp[i] + dp[i - nums[j]];
                }
            }
        }
        return dp[target];
    }
}