20200408——第三十九题 组合总和

class Solution {
    List<List<Integer>> lists = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates == null && target <0 || candidates.length<0){
            return null;
        }
        List<Integer> list = new ArrayList<>();
        Core(0,candidates,target,list);
        return lists;
    }
    public void Core(int start ,int[] candidates ,int target,List<Integer> list){
        if(target <0){
            return ;
        }else if(target == 0){
            lists.add(new ArrayList<>(list));
        }else{
            for(int i = start;i<candidates.length;++i){
                list.add(candidates[i]);
                Core(i,candidates,target-candidates[i],list);
                list.remove(list.size()-1);
            }
        }
    }
}

用到了回溯法, 别忘了剪枝,就是当前节点的值,小小于减去的值。
在这里插入图片描述
减去的值,不能比上一个减去的值少。
在这里插入图片描述

发布了955 篇原创文章 · 获赞 43 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36344771/article/details/105394710