2-22-lc39组合总和

39. 组合总和

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates==null)return res;
        dfs(target,0,new Stack<Integer>(), candidates);
        return res;
    }
    public void dfs(int target, int index, Stack<Integer> tmp, int[] candidates){
        if(target==0){//这里的target是candidate与目标值的差值
            res.add(new ArrayList<>(tmp));
            return;
        }
        for(int i=index;i<candidates.length;i++){//index 开始实现剪枝
            if(candidates[i]<=target){//目标值减去元素值
                tmp.push(candidates[i]);
                dfs(target-candidates[i],i,tmp,candidates);
                tmp.pop();
            }
        }
    }
}

 

posted @ 2022-02-22 14:36  Wind·Chaser  阅读(25)  评论(0编辑  收藏  举报