首页 > 其他 > 详细

Combination Sum I and II

时间:2015-04-14 08:24:32      阅读:189      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!