Leetcode 40. Combination Sum II (Medium) (java)
Tag: Array, Backtracking
Difficulty: Medium
/*
40. Combination Sum II (Medium)
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.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
*/
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(candidates);
combinationSum2(candidates, target, 0, res, new ArrayList<>());
return res;
}
private void combinationSum2(int[] candidates, int target, int start, List<List<Integer>> res, List<Integer> res_sub) {
if (start > candidates.length || target < 0) {
return;
} else if (target == 0) {
res.add(new ArrayList(res_sub));
return;
}
for (int i = start; i < candidates.length; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
res_sub.add(candidates[i]);
combinationSum2(candidates, target - candidates[i], i + 1, res, res_sub);
res_sub.remove(res_sub.size() - 1);
}
}
}