leetcode39_组合求和

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> combine = new ArrayList<>();
    dfs(candidates, target, combine, ans, 0);
    return ans;
}

public void dfs(int[] candidates, int target, List<Integer> combine, List<List<Integer>> ans, int idx) {
    if(idx == candidates.length) return;
    if(0 == target) {
        ans.add(new ArrayList<>(combine));
        return;
    }
    dfs(candidates, target, combine, ans, idx+1);
    if(target - candidates[idx] >= 0){
        combine.add(candidates[idx]);
        dfs(candidates, target-candidates[idx], combine, ans, idx);
        combine.remove(combine.size()-1);
    }
}
posted @ 2022-02-12 23:16  明卿册  阅读(23)  评论(0)    收藏  举报