您的位置:首页 > 其它

40. Combination Sum II

2016-02-28 08:47 323 查看
和39. Combination Sum基本是一样的,就是上一次迭代的时候从这个数的位置开始,不可以重复的话,就从下一个位置开始

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
helper(candidates, target, res, new ArrayList<Integer>(), 0, 0);
return res;
}

public void helper(int[] candidates, int target, List<List<Integer>> res, List<Integer> item, int start, int curSum) {
if(curSum > target) {
return;
}
if(curSum == target) {
if(!res.contains(item)) {
res.add(new ArrayList<Integer>(item));
}
return;
}
for(int i = start; i < candidates.length; i++) {
item.add(candidates[i]);
helper(candidates, target, res, item, i + 1, curSum + candidates[i]);
item.remove(item.size() - 1);
}
return;
}


基本无bug一遍通过的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: