zoukankan      html  css  js  c++  java
  • <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);
            }
        }
    }
  • 相关阅读:
    SecureCRT乱码问题简单的解决办法
    安家博客园,开始java web 之旅
    Java Service Wrapper使用心得
    vsftp折腾
    mysql更改数据库表名称和svnerve启动版本库命令、执行jar命令
    Linux 命令积累2
    二进制与十进制的转换
    java Map代替List在for循环中的应用
    Optional 的应用
    java Date、java.sql.Date、localTime、SimpleDateFormat的格式及应用
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11906271.html
Copyright © 2011-2022 走看看