Leetcode - Combination Sum IV

My code:

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

这道题目也是DP。
然后 dp[i] 表示 target = i 时,需要的次数。
[1, 2, 3] 4

1 2 3 4
0 0 0

将 nums已有的数字反映在 dp[] 上
1 2 3 4
1 1 1

扫描1, 看看之前的数能否通过 [1, 2, 3]到达它。 无
1 2 3 4
1 1 1

扫描 2, 看看之前的数能否通过[1, 2, 3]到达它。有
1 + 1, 所以 dp[2] += dp[2 - 1]
1 2 3 4
1 2 1

扫描3,看看之前的数能否通过[1, 2, 3] 到达它。有
1 + 2, 所以 dp[3] += dp[3 - 2]
2 + 1, 所以 dp[3] += dp[3 - 1]
1 2 3 4
1 2 4

以此类推,可以得到:
dp[4] = 7

然后写出代码

其实一开始写的是 recursion + cache 的做法。
My code:

public class Solution {
    private int ret = 0;
    public int combinationSum4(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int[] cache = new int[target + 1];
        return helper(0, 0, nums, target, cache);
    }
    
    private int helper(int begin, int sum, int[] nums, int target, int[] cache) {
        if (begin >= nums.length) {
            if (sum == target) {
                return 1;
            }
            else {
                return 0;
            }
        }
        else if (sum > target) {
            return 0;
        }
        else if (sum == target) {
            return 1;
        }
        else if (cache[target - sum] != 0) {
            return cache[target - sum];
        }
        else {
            int ans = 0;
            for (int i = 0; i < nums.length; i++) {
                ans += helper(i, sum + nums[i], nums, target, cache);
            }
            cache[target - sum] = ans;
            return ans;
        }
    }
    
    public static void main(String[] args) {
     Solution test = new Solution();
     int[] nums = new int[]{3, 33, 333};
     int ret = test.combinationSum4(nums, 10000);
     System.out.println(ret);
    }
}

后来TLE,仔细想想,发现复杂度实在太大了!
即使有cache,也会有大量的stack出现!

所以只能有 Iteration DP来解决。

Anyway, Good luck, Richardo! -- 08/21/2016

你可能感兴趣的:(Leetcode - Combination Sum IV)