zoukankan      html  css  js  c++  java
  • 39. 组合总和

    思路: 使用dfs递归实现的深度优先搜索来实现对数据的查找

    通过对原数组进行排序来实现剪枝

    代码:

        /**
         * @Description: 使用dfs递归来实现的深度优先搜索来进行数据的查找
         * @auther: DaleyZou
         * @date: 17:11 2018-8-22
         * @param: candidates
         * @param: target
         * @return: java.util.List<java.util.List<java.lang.Integer>>
         */
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> resultList = new ArrayList<>();
            List<Integer> result = new ArrayList<>();
            Arrays.sort(candidates); // 剪枝
            dfs(candidates, resultList, result, 0, target);
            return resultList;
        }
    
        private void dfs(int[] candidates, List<List<Integer>> resultList, List<Integer> result, int start, int target) {
            if (target < 0){            // target不符合
                return;
            }else if (target == 0){   // target符合
                resultList.add(new ArrayList<>(result));
            }else {                  // 继续进行数的查找
                for (int i = start; i < candidates.length; i++){
                    result.add(candidates[i]);
                    dfs(candidates, resultList, result, i, target - candidates[i]);
                    result.remove(result.size() - 1);     // 数查找完后要进行回溯
                }
            }
        }
    
  • 相关阅读:
    编程珠玑(续) 读书笔记 -(第三章 程序员的忏悔)
    java for循环
    java 中的 instanceof
    大脑学习
    voa 2015.4.29
    编程珠玑(续) 读书笔记 -(前言+第一章性能监视工具)
    voa 2015 / 4 / 27
    voa 2015 / 4 / 26
    背包问题 算法实现
    LCS 算法实现
  • 原文地址:https://www.cnblogs.com/daleyzou/p/9519277.html
Copyright © 2011-2022 走看看