题目链接
思路
- 首先要明白为什么会重复。以[2,2,2,3] 7 为例。因为2重复了三次,所以有可能选择答案的索引为[0,1,3]、[0,2,3]、[1,2,3]
- 之所以会这样是因为可能我们选择了第0个、第1个元素;或者是选择了第0个元素,没选择第1个元素,又选择了第2个元素。对于元素不重复的数组,这样是没问题的。但是对于元素重复的数组,这样就会产生重复的答案
- 所以解决办法为,当我们决定不选择某个元素时,在调用helper函数时,index应该传下一个和该索引元素不同的元素的索引
- 回到我们的例子中,也就是说如果某一步我们决定不再选择2时,下一步的helper函数应该传入的索引为3,也就是元素3对应的索引
public class Solution {
List<List<Integer>> result;
int[] nums;
int target;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
result = new ArrayList<>();
nums = candidates;
this.target = target;
Arrays.sort(nums);
helper(new ArrayList<>(), 0, 0);
return result;
}
private void helper(List<Integer> combination, int index, int sum) {
if (sum == target)
result.add(new ArrayList<>(combination));
else if (index < nums.length && sum < target) {
int nextIndex = index + 1;
while (nextIndex < nums.length && nums[index] == nums[nextIndex])
nextIndex++;
helper(combination, nextIndex, sum);
combination.add(nums[index]);
helper(combination, index + 1, sum + nums[index]);
combination.remove(combination.size() - 1);
}
}
}