码迷,mamicode.com
首页 > 其他好文 > 详细

40. Combination Sum II

时间:2017-09-24 09:45:42      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:array   return   private   als   color   ons   boolean   continue   nat   

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ret=new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        boolean[] used=new boolean[candidates.length];
        generateCombination(new ArrayList<Integer>(), 0, target, used, ret, candidates);
        return ret;
    }
    private void generateCombination(List<Integer> list, int idx, int target, boolean[] used, List<List<Integer>> combs, int[] candidates){
        if(target==0)
        {
            combs.add(new ArrayList<Integer>(list));
            return;
        }
        if(idx>=candidates.length||target<0)
            return;
        generateCombination(list, idx+1, target, used, combs, candidates);
        if(idx>0&&used[idx-1]==false&&candidates[idx-1]==candidates[idx])
            return;
        list.add(candidates[idx]);
        used[idx]=true;
        generateCombination(list, idx+1, target-candidates[idx], used, combs, candidates);
        list.remove(list.size()-1);
        used[idx]=false;
    }
}

 

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> combs=new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        generateCombination(new ArrayList<Integer>(), 0, target, combs, candidates);
        return combs;
    }
    private void generateCombination(List<Integer> list, int idx, int target, List<List<Integer>> combs, int[] candidates){
        if(target==0)
        {
            combs.add(new ArrayList<Integer>(list));
            return;
        }
        if(idx>=candidates.length||target<0)
            return;
        for(int i=idx;i<candidates.length;i++)
        {
            if(i>idx&&candidates[i]==candidates[i-1])
                continue;
            list.add(candidates[i]);
            generateCombination(list, i+1, target-candidates[i], combs, candidates);
            list.remove(list.size()-1);
        }
    }
}

 

40. Combination Sum II

标签:array   return   private   als   color   ons   boolean   continue   nat   

原文地址:http://www.cnblogs.com/asuran/p/7584720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!