class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates, 0, new ArrayList<>(), target, 0);
return ans;
}
private void dfs(int[] candidates, int index, List<Integer> path, int target, int sum) {
if (sum > target) return;
if (sum == target) {
ans.add(new ArrayList<>(path));
return;
}
if (index == candidates.length) {
return;
}
int end = index + 1;
while (end < candidates.length && candidates[end] == candidates[index]) end++;
dfs(candidates, end, path, target, sum);
int presize = path.size();
for (int i = index; i < end; i++) {
sum += candidates[index];
path.add(candidates[index]);
dfs(candidates, end, path, target, sum);
}
path.subList(presize, path.size()).clear();
}
}