您的位置:首页 > 其它

LeetCode Combination Sum II

2015-09-28 23:37 302 查看
原题链接在这里:https://leetcode.com/problems/combination-sum-ii/

本题与Combination Sum非常相似,不同就在于本题不可以重复使用元素。其实只是递归时,start的参数更改为i+1即可。

Note: 1. 即使本题不可以使用重复元素但也需要小心res 里加了重复的item. e.g. target = 1, candidates = [1,1], res中会出现两个[1]. 所以在加入res前需校验res中是否已有相同item.

这个方法同样适用于Combination Sum.

AC Java:

public class Solution {
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,0,new ArrayList<Integer>(),res);
return res;
}
private void helper(int[] candidates, int target, int start, List<Integer> item, List<List<Integer>> res){
if(target == 0){
if(!res.contains(item)){
res.add(new ArrayList<Integer>(item));
}
return;
}
if(target < 0){
return;
}
for(int i = start; i<candidates.length; i++){
item.add(candidates[i]);
helper(candidates,target-candidates[i],i+1,item,res);
item.remove(item.size()-1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: