[LeetCode] Combination Sum

据说linkedin会考。。。没啥难的倒是

public class Solution {
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        Arrays.sort(num);
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if(num.length == 0) {
            return ret;
        } else {
            combinationSum2Helper(num,target,0,0,ret,new ArrayList());
        }
        return ret;
    }
    public void combinationSum2Helper(int [] num, int target, int curSum, int curIndex, List<List<Integer>> ret, List<Integer> l) {
        if(curSum > target) {
            return;
        }
        if(curSum == target) {
            ret.add(l);
            return;
        }
        if(curIndex >= num.length) {
            return;
        }
        for(int i = curIndex; i < num.length; i++) {
            //this is the only line added on top of combination sum 1
            if(i > curIndex && num[i] == num[i-1]) {
                continue;
            }
            l.add(num[i]);
            combinationSum2Helper(num,target,curSum + num[i],i+1,ret,new ArrayList(l));
            l.remove(l.size()-1);
        }
    } 
}
posted on 2015-03-31 14:12  Seth_L  阅读(111)  评论(0编辑  收藏  举报