Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

1
2
3
4
5
6
7
8
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
1
2
3
4
5
6
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

给定的candidates中可能有duplicates, 所以sort并if (i > start && nums[i] == nums[i-1]) continue;去掉duplicates;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<List<Integer>> combinationSum2(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
dfs(list, new ArrayList<>(), nums, target, 0);
return list;
}

public void dfs(List<List<Integer>> list, List<Integer> arr, int[] nums, int target, int start) {
if (target < 0) return;
else if (target == 0) list.add(new ArrayList<>(arr));
else {
for (int i = start; i < nums.length; ++i) {
if (i > start && nums[i] == nums[i-1]) continue;
arr.add(nums[i]);
dfs(list, arr, nums, target - nums[i], i + 1); // i, can be reused
arr.remove(arr.size() - 1);
}
}
}
}