40 Combination Sum II
1. Question
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]2. Implementation
3. Time & Space Complexity
Last updated
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]Last updated
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> combinations = new ArrayList<>();
Arrays.sort(candidates);
getCombinations(candidates, 0, 0, target, combinations, res);
return res;
}
public void getCombinations(int[] candidates, int index, int sum, int target, List<Integer> combinations, List<List<Integer>> res) {
if (sum > target) {
return;
}
if (sum == target) {
res.add(new ArrayList<>(combinations));
return;
}
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i - 1] == candidates[i]) {
continue;
}
combinations.add(candidates[i]);
getCombinations(candidates, i + 1, sum + candidates[i], target, combinations, res);
combinations.remove(combinations.size() - 1);
}
}
}