码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 377: Combination Sum IV

时间:2017-08-30 15:39:42      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:ack   turn   style   tco   pack   force   public   like   class   

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;
        
    }
}

 

LeetCode 377: Combination Sum IV

标签:ack   turn   style   tco   pack   force   public   like   class   

原文地址:http://www.cnblogs.com/shuashuashua/p/7452978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!