组合总和 DFS + 回溯 + 剪枝

题目:

  给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

  candidates 中的数字可以无限制重复被选取。

思路:

  dfs + 回溯 + 剪枝

 


(一)代码

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //dfs + 回溯 + 剪枝
        //结果 list
        List<List<Integer>> reslist = new ArrayList<List<Integer>>();
        //路径list
        List<Integer> path = new ArrayList<Integer>();
        //注意 排序
        Arrays.sort(candidates);
        
        deepFindRes(candidates,target,reslist,path,0);
        return reslist;
    }

    /**
     * @param candidates   原数组
     * @param target       目标和
     * @param reslist      结果list
     * @param path         路径list
     * @param start        开始位置
     */
    public void deepFindRes(int[] candidates, int target,List<List<Integer>> reslist,List<Integer> path , int start){
        //递归出口
        if(target == 0){
            //注意这里
            reslist.add(new ArrayList<>(path));
            return;
        }
        for(int i = start ; i < candidates.length && target >= candidates[i];  i++){
            path.add(candidates[i]);
            //递归
            deepFindRes(candidates,target - candidates[i],reslist,path,i);
            //剪枝
            path.remove(path.size() - 1);
        }
    }

 


 

 

    

       不好搞那

 

posted @ 2021-06-23 15:57  朝才  阅读(29)  评论(1编辑  收藏  举报