• 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);     // 数查找完后要进行回溯
                }
            }
        }
    
  • 相关阅读:
    作业3
    数组求和
    2.自己的Github试用过程
    2.自己的Github注册流程
    图片左右滑动整理为插件
    artDialog中的time参数,ajax请求中的异步与同步
    简单的图片放大镜效果插件
    3月份学习安排
    前端好的网站
    web app开发中遇到的问题
  • 原文地址:https://www.cnblogs.com/daleyzou/p/9519277.html
Copyright © 2020-2023  润新知