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


    class Solution {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new LinkedList<>();
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            dfs(target,candidates,0,0);
            return res;
        }
    
        public void dfs(int target,int[] candidates,int cur,int start){
            if(cur > target ) return;
            if(cur == target){
                res.add(new ArrayList<>(list));
                return;
            }
            for(int i=start;i<candidates.length;i++){//从start开始
                list.add(candidates[i]);
                dfs(target,candidates,cur+candidates[i],i);//这里是i不是i+1
                list.remove(list.size()-1);
            }
        }
    }
    
    


    
    class Solution {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new LinkedList<>();
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            dfs(target,candidates,0,0);
            return res;
        }
    
        public void dfs(int target,int[] candidates,int cur,int start){
            if(cur > target) return;
            if(cur == target){
                res.add(new ArrayList(list));
                return;
            }
            for(int i=start;i<candidates.length;i++){//从start开始
               if(i!=start && candidates[i] == candidates[i-1]) continue;//去重
                list.add(candidates[i]);
                dfs(target,candidates,cur+candidates[i],i+1);//i+1不重复取
                list.remove(list.size()-1);
            }
        }
    
    
    }
    
    
  • 相关阅读:
    hdu6148 Valley Numer
    NOI2007 生成树计数
    bzoj3336 Uva10572 Black and White
    hdu1693 eat the trees
    【模板】插头dp
    bzoj4712 洪水
    ZJOI2010 基站选址
    poj2376 Cleaning Shifts
    bzoj4367 [IOI2014]holiday假期
    bzoj4951 [Wf2017]Money for Nothing
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13644015.html
Copyright © 2011-2022 走看看