去年做的有重复输出是错误的,我直接调用了HashSet企图用这个结构把重复数组删除。这个方法assume对于不同的List含有相同的integer,他们的HashCode是相同的!(不可以这样assume)
public List>combinationSum2(int[] num, int target) {
Arrays.sort(num);
return helper(num, target, 0);
}
List> helper(int[]candidates, int target, int start) {
List> result = new LinkedList>();
if (target == 0) {
List list= new LinkedList();
result.add(list);
returnresult;
}
if (target < candidates[0]) {
returnresult;
}
for (int i = start; i < candidates.length;i++) {
if (i >start && candidates[i] == candidates[i-1]) { //attention, do not use i>0, made first errorhere
continue;
}
List>preResult = helper(candidates, target - candidates[i], i +1);
for (Listlist : preResult) {
list.add(0,candidates[i]);
result.add(list);
}
}
return result;
}
Combination Sum II:
public class Solution {
}