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);
            }
        }

        

           不好搞那

  • 相关阅读:
    Python Virtualenv 虚拟环境
    二叉树的左视图和右视图
    Vxlan简介
    2、程序的基本结构
    chef cookbook 实战
    eclipse 搭建ruby环境
    linux 安装软件出现/tmp 磁盘不足时 解决方案
    Python 可变对象与不可变对象
    Chapter 4-5
    Chapter 3
  • 原文地址:https://www.cnblogs.com/misscai/p/14923114.html
Copyright © 2011-2022 走看看