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);
            }
        }
    }
  • 相关阅读:
    使用Hibernate Validator来帮你做数据校验
    关于Picasso load本地图片显示失败的探究
    Android 动画机制与使用技巧
    Android-Volley详解
    源码级分析Android系统启动流程
    Android端百度地图API使用详解
    Eclipse中R文件不能自动生成
    一天掌握Android JNI本地编程 快速入门
    网络编程之PC版与Android手机版带断点续传的多线程下载
    《MySQL必知必会》读书笔记
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11906271.html
Copyright © 2011-2022 走看看