zoukankan      html  css  js  c++  java
  • 组合总和 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);
            }
        }

        

           不好搞那

  • 相关阅读:
    css 分类+选择器
    emmet语法
    程序员能力矩阵
    时间管理

    java 内存 解析
    SQL 查询优化
    2016 书单计划
    ssh框架;
    Mybatis;
  • 原文地址:https://www.cnblogs.com/misscai/p/14923114.html
Copyright © 2011-2022 走看看