Thinking process
each element may only be used once
but there're duplicates
Mistakes
- how to avoid duplicates answer?
- the number that is equal to its previous one but is larger than index
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
//validate input
if (candidates.length == 0) return result;
Arrays.sort(candidates);
findCombinationSum(candidates, target, result, new ArrayList<>(), 0);
return result;
}
private void findCombinationSum(int[] candidates, int target, List<List<Integer>> result,
List<Integer> list, int index){
//end conditions
if (target < 0) {
return;
} else if (target == 0) {
result.add(new ArrayList<>(list));
return;
}
for (int i = index; i < candidates.length; ++i) {
if (i > index && candidates[i] == candidates[i - 1]) continue;
list.add(candidates[i]);
findCombinationSum(candidates, target - candidates[i], result, list, i + 1);
list.remove(list.size() - 1);
}
}
}