Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
Example:
Given candidate set [10,1,6,7,2,1,5] and target 8,
A solution set is:
[
[1,7],
[1,2,5],
[2,6],
[1,1,6]
]
Solution:
This question is similar to k Sum II. However, we need to avoid duplicate combinations. Therefore, we should try each unique number at every level of dfs.
Code:
public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(num);
dfs(num, target, 0, new ArrayList<Integer>(), res);
return res;
}
private void dfs(int[] num, int target, int index, List<Integer> path,
List<List<Integer>> res) {
if (target == 0) {
res.add(new ArrayList<>(path));
return;
}
if (index >= num.length || target < 0) {
return;
}
int prev = -1;
for (int i = index; i < num.length; i++) {
if (num[i] != prev) {
path.add(num[i]);
dfs(num, target - num[i], i + 1, path, res);
prev = num[i];
path.remove(path.size() - 1);
}
}
}
}