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);
            }
        }
    }
  • 相关阅读:
    HTML5中表单的创建
    防冲撞协议原理实验报告
    yii2.0 Activeform表单部分组件使用方法 [ 2.0 版本 ]
    Yii正则验证
    Yii2用Gii自动生成Module+Model+CRUD
    yii2框架安装运行init.bat报错php.exe不是内部或外部命令
    YII2.0安装教程,数据库配置前后台 [ 2.0 版本 ]
    ignore_user_abort函数制定计划任务
    php 常用的系统函数
    php常用字符串处理函数
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11906271.html
Copyright © 2011-2022 走看看