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

<BackTracking> Combination, DFS :216 DP: 377

时间:2019-11-22 01:28:44      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:dex   结束   track   style   oid   方法   超时   get   null   

216. Combination Sum III

保证subset.size( ) == k && target == 0的时候结束DFS

subset.size( ) > k || target < 0返回。

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        if(k <= 0 || n < 1) return res;
        dfs(res, new ArrayList<Integer>(), k, n, 1);
        return res;
    }
    
    private void dfs(List<List<Integer>> res, List<Integer> subset, int k, int target, int index){
        if(subset.size() > k && target < 0)
            return;
        if(subset.size() == k && target == 0){
            res.add(new ArrayList<Integer>(subset));
            return;            
        }
        for(int i = index; i <= 9; i++){
            subset.add(i);
            dfs(res, subset, k, target - i, i + 1);
            subset.remove(subset.size() - 1);
        }
    }
}

377. Combination Sum IV

DFS: 此方法超时

class Solution {
    int count;
    public int combinationSum4(int[] nums, int target) {
        if(nums == null || nums.length == 0) return 0;
        dfs(nums, target, new ArrayList<Integer>());
        return count;
    }
    
    private void dfs(int[] nums, int target, List<Integer> subset){
        if(target == 0){
            count++;
            return;
        }
        if(target < 0){
            return;
        }
        for(int i = 0; i < nums.length; i++){
            subset.add(nums[i]);
            dfs(nums, target - nums[i], subset);
            subset.remove(subset.size() - 1);
        }
    }
}

DP: i - nums[ j ]表 当前nums[ j ]与之前comb[ ] 中的组合数字继续组合得到target。

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

 

<BackTracking> Combination, DFS :216 DP: 377

标签:dex   结束   track   style   oid   方法   超时   get   null   

原文地址:https://www.cnblogs.com/Afei-1123/p/11909259.html

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