40. Combination Sum II
Asked at 15Meta40Microsoft38Bloomberg37Google34Amazon33Rakuten100Snap80Morgan Stanley54Adobe44Walmart Labs43Zoho42LinkedIn37Oracle35TikTok35Salesforce28
Problem
candidates may contain duplicates. Return every unique combination that sums to target, using each array element at most once, with no duplicate combinations.
Example: candidates = [10,1,2,7,6,1,5], target = 8 → [[1,1,6],[1,2,5],[1,7],[2,6]]
Constraints: up to 100 candidates; target ≤ 30.
Each number used once (i + 1) and the input has duplicates → sort and skip equal neighbours at the same depth.
Complexity: O(2ⁿ).
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res, path = [], []
def bt(start, rest):
if rest == 0:
res.append(path[:])
return
for i in range(start, len(candidates)):
if i > start and candidates[i] == candidates[i - 1]:
continue
if candidates[i] > rest:
break
path.append(candidates[i])
bt(i + 1, rest - candidates[i])
path.pop()
bt(0, target)
return res
assert sorted(map(sorted, Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8))) == sorted(map(sorted, [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]))
assert sorted(map(sorted, Solution().combinationSum2([2, 5, 2, 1, 2], 5))) == [[1, 2, 2], [5]]
assert Solution().combinationSum2([1], 2) == []
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
bt(candidates, 0, target, new ArrayList<>(), res);
return res;
}
private void bt(int[] c, int start, int rest, List<Integer> path, List<List<Integer>> res) {
if (rest == 0) { res.add(new ArrayList<>(path)); return; }
for (int i = start; i < c.length && c[i] <= rest; i++) {
if (i > start && c[i] == c[i - 1]) continue;
path.add(c[i]);
bt(c, i + 1, rest - c[i], path, res);
path.remove(path.size() - 1);
}
}
}
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
res, path := [][]int{}, []int{}
var bt func(start, rest int)
bt = func(start, rest int) {
if rest == 0 {
res = append(res, append([]int{}, path...))
return
}
for i := start; i < len(candidates) && candidates[i] <= rest; i++ {
if i > start && candidates[i] == candidates[i-1] {
continue
}
path = append(path, candidates[i])
bt(i+1, rest-candidates[i])
path = path[:len(path)-1]
}
}
bt(0, target)
return res
}