<BackTracking> dfs: 39 40

39. Combination Sum

Combination,组合问题用DFS罗列全部的答案。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        dfs(candidates, target, 0, res, new ArrayList<Integer>());
        return res;
    }
    
    //1.定义
    private void dfs(int[] candidates, int target, int index, List<List<Integer>> res, List<Integer> subset){
        //3.出口
        if(target == 0){
            res.add(new ArrayList<Integer>(subset));
            return;
        }
        if(target < 0){
            return;
        }
        //2.拆解
        for(int i = index; i < candidates.length; i++){
            subset.add(candidates[i]);
            dfs(candidates, target - candidates[i], i, res, subset);
            subset.remove(subset.size() - 1);
        }

    }
}

40. Combination Sum II

1.  为了防止candidates[ ]中的数字被重复使用,DFS中的index使用 i + 1。

2.防止答案中出现重复的数字使用情况,

 if(i > index && candidates[i] == candidates[i - 1]) continue;
即当前层的数字只能被重复使用一次。
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        Arrays.sort(candidates);
        dfs(candidates, target, 0, res, new ArrayList<>());
        return res;
    }
    
    private void dfs(int[] candidates, int target, int index, List<List<Integer>> res, List<Integer> subset){
        //出口
        if(target == 0){
            res.add(new ArrayList<Integer>(subset));
            return;
        }
        if(target < 0){
            return;
        }
        //拆解
        for(int i = index; i < candidates.length; i++){
            if(i > index && candidates[i] == candidates[i - 1]) continue;
            subset.add(candidates[i]);
            dfs(candidates, target - candidates[i], i + 1, res, subset);
            subset.remove(subset.size() - 1);
        }
    }
}
原文地址:https://www.cnblogs.com/Afei-1123/p/11906271.html