zoukankan      html  css  js  c++  java
  • lintcode-135-数字组合

    public class Solution {
        /**
         * @param candidates: A list of integers
         * @param target: An integer
         * @return: A list of lists of integers
         */
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            // write your code here
            ArrayList<List<Integer>> res = new ArrayList<>();
            Arrays.sort(candidates);
            dfs(0,0,candidates,res,target,new ArrayList<Integer>());
            return res;
        }
    
        private void dfs(int lastSum,
                         int depth,int[] candidates,
                         ArrayList<List<Integer>> res,
                         int target,
                         List<Integer> lastList) {
            if(lastSum>target)
                return;
            if(lastSum==target){
                res.add(new ArrayList<>(lastList));
                return;
            }
            for(int i=depth;i<candidates.length;++i){
                if(i!=0&&candidates[i]==candidates[i-1])
                    continue;
                lastList.add(candidates[i]);
                dfs(lastSum+candidates[i],i,candidates,res,target,lastList);
                lastList.remove(lastList.size()-1);//从底层回溯到这个位置,说明上一个数据已经利用完了,可以滚蛋了(每层只能选一个数据啊)
            }
        }
    
        public static void main(String[] args) {
            Solution solution = new Solution();
            List<List<Integer>> lists = solution.combinationSum(new int[]{2, 3, 6, 7}, 7);
        }
    }
  • 相关阅读:
    PHP入门03 -- 数组与数据结构
    PHP入门02 -- 函数
    PHP入门01 -- 基本语法
    node文章
    Mongodb08
    Mongodb07
    ISO处理jq事件
    map
    Django自定义模板
    JS this指向
  • 原文地址:https://www.cnblogs.com/t1314/p/12511223.html
Copyright © 2011-2022 走看看