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

It's like the packing problem.

 

 

Brute force:

class Solution {
    public int combinationSum4(int[] nums, int target) {
        if (target < 0) {
            return 0;
        }
        if (target == 0) {
            return 1;
        }
        int result = 0;
        for(int num : nums) {
            result += combinationSum4(nums, target - num);
        }
        
        return result;
        
    }
}

 

posted on 2017-08-30 14:28  keepshuatishuati  阅读(83)  评论(0编辑  收藏  举报