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

Combination Sum I and II

时间:2015-04-14 08:25:42      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

比较典型的helper的题目,现在我还搞不太清楚dfs之类的,只能用helper来统称了,你明白那个调调就行

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> res =new ArrayList<ArrayList<Integer>>();
        Arrays.sort(candidates);
        if(candidates == null || candidates.length<1) return res;
        helper( candidates, target, res, new ArrayList<Integer>(), 0);
        return res;
    }
    public void helper(int[] c, int t,ArrayList<ArrayList<Integer>> res, ArrayList<Integer> item, int start ){
        if(0==t){
             res.add(new ArrayList<Integer> (item));//res.add(item);
            return; // 提速
        }
        if(0>t) return;
        for(int i=start; i< c.length; i++){
            if(i>start && c[i-1]==c[i]) continue;
            item.add(c[i]);
            helper(c, t-c[i], res, item, i); // 如果i变成i+1,则是不允许重复元素出现,而i,并且循环从i=start开始,则允许了重复元素构建target的可能性,一并解决了II
            item.remove(item.size()-1);
        }
    }
}

 

Combination Sum I and II

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4423899.html

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