Combination Sum I and II

比较典型的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);
        }
    }
}

 

posted @ 2015-04-14 06:59  世界到处都是小星星  阅读(136)  评论(0编辑  收藏  举报