Combination Sum II (LeetCode 40): Solution and Explanation
Given a list of candidate numbers that may contain duplicates and a target, return every unique combination whose values add up to the target. Each candidate can be used at most once, and the same combination must not appear twice.
Watch it run step by step
Try your own input and write the code →Intuition
This is a subset search with a sum constraint. The brute force is to enumerate every subset of candidates, keep the ones that sum to the target, and remove duplicate combinations at the end. With up to 100 candidates that is hopeless, and deduplicating after the fact means you already paid for all the repeated work.
Two observations make it manageable. First, each element is a binary choice, take it or leave it, so a recursion over indices is natural, and it can stop early once the running total exceeds the target because all candidates are positive. Second, duplicate values in the input are what create duplicate combinations. If the candidates are [1,2,2,2,5] and the target is 5, taking the first 2 and the third 2 gives the same [1,2,2] as taking the first and second.
Sorting fixes the duplicate problem the same way it does in Subsets II. Once equal values are adjacent, treat a run of equal values as a choice of how many copies to take. The include branch takes the current copy and moves to the next index, which might be another copy. The exclude branch skips past every remaining copy of the value, meaning you have decided to take no more of it. Each combination is then produced exactly once.
The reference code tracks the current combination cur and its running total, records a copy whenever the total hits the target, and returns as soon as the total overshoots or the index runs off the end.
Approach: Sort and backtrack with duplicate skipping
- Sort
candidatesso equal values are adjacent. - Define
dfs(i, cur, total). Iftotal == target, append a copy ofcurtoresand return. - If
total > targetori == len(candidates), return, since this branch cannot produce a valid combination. - Include branch: append
candidates[i], recurse withdfs(i + 1, cur, total + candidates[i]), then pop. - Advance
iwhilecandidates[i] == candidates[i + 1]so the exclude branch skips every copy of the current value. - Exclude branch: call
dfs(i + 1, cur, total). Start everything withdfs(0, [], 0).
Step-by-step example
candidates = [2,5,2,1,2], target = 5
- Sorting gives [1,2,2,2,5].
- Include 1 (total 1), include the 2 at index 1 (total 3), include the 2 at index 2 (total 5). The total equals the target, so [1,2,2] is recorded.
- Back with [1,2] at index 2, the exclude branch skips index 3 (also 2) and tries 5 at index 4, which gives 8 and overshoots, so nothing is added.
- Back with [1] at index 1, the exclude branch skips all three 2s and tries 5, reaching 6, which overshoots.
- Back at the root, exclude 1. Paths starting with 2 reach totals of 2, 4 and 6, or overshoot with 5, so none hits exactly 5.
- Finally the branch that excludes 1 and all the 2s includes 5 alone, reaching total 5 and recording [5]. The answer is [[1,2,2],[5]].
Code: Python, Java, C++
1class Solution:
2 def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
3 res = []
4 candidates.sort()
5
6 def dfs(i, cur, total):
7 if total == target:
8 res.append(cur[::])
9 return
10 if total > target or i == len(candidates):
11 return
12
13 cur.append(candidates[i])
14 dfs(i + 1, cur, total + candidates[i])
15 cur.pop()
16
17 while i + 1 < len(candidates) and candidates[i] == candidates[i + 1]:
18 i += 1
19 dfs(i + 1, cur, total)
20
21 dfs(0, [], 0)
22 return res1class Solution {
2 public List<List<Integer>> combinationSum2(int[] candidates, int target) {
3 List<List<Integer>> res = new ArrayList<>();
4 Arrays.sort(candidates);
5 dfs(0, new ArrayList<>(), 0, candidates, target, res);
6 return res;
7 }
8
9 private void dfs(int i, List<Integer> cur, int total, int[] candidates, int target, List<List<Integer>> res) {
10 if (total == target) {
11 res.add(new ArrayList<>(cur));
12 return;
13 }
14 if (total > target || i == candidates.length) {
15 return;
16 }
17
18 cur.add(candidates[i]);
19 dfs(i + 1, cur, total + candidates[i], candidates, target, res);
20 cur.remove(cur.size() - 1);
21
22 while (i + 1 < candidates.length && candidates[i] == candidates[i + 1]) {
23 i++;
24 }
25 dfs(i + 1, cur, total, candidates, target, res);
26 }
27}1class Solution {
2public:
3 vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
4 vector<vector<int>> res;
5 vector<int> cur;
6 sort(candidates.begin(), candidates.end());
7 dfs(0, cur, 0, candidates, target, res);
8 return res;
9 }
10
11 void dfs(int i, vector<int>& cur, int total, vector<int>& candidates, int target, vector<vector<int>>& res) {
12 if (total == target) {
13 res.push_back(cur);
14 return;
15 }
16 if (total > target || i == candidates.size()) {
17 return;
18 }
19
20 cur.push_back(candidates[i]);
21 dfs(i + 1, cur, total + candidates[i], candidates, target, res);
22 cur.pop_back();
23
24 while (i + 1 < candidates.size() && candidates[i] == candidates[i + 1]) {
25 i++;
26 }
27 dfs(i + 1, cur, total, candidates, target, res);
28 }
29};Time and space complexity
O(n × 2^n)
In the worst case the recursion explores every include or exclude choice, giving up to 2^n leaves, and copying a combination into the result costs up to O(n). Pruning on total > target usually cuts this down sharply.
O(n)
The recursion depth and the cur list are bounded by the number of candidates, ignoring the space for the output.
Other approaches
Loop-based backtracking (time O(n × 2^n), space O(n))
From position start, loop j over the remaining indices, skip j when it equals the previous value at the same depth (j > start and candidates[j] == candidates[j - 1]), and break as soon as a value exceeds the remaining target. It is the most common variant and prunes slightly better thanks to the early break.
Counter-based recursion (time O(n × 2^n), space O(n))
Count each distinct value, then recurse over distinct values choosing how many copies to take, from zero up to its count. This avoids the skip loop entirely and is clean when many duplicates exist.
Common mistakes
- Recursing with
iinstead ofi + 1on the include branch, which reuses the same candidate and turns this into the unlimited-use version of the problem. - Forgetting to sort, so the duplicate skip compares unrelated neighbors and repeated combinations appear in the output.
- Checking
i == len(candidates)beforetotal == target, which drops combinations that reach the target using the last element. - Appending
curdirectly instead of a copy, so every stored combination is mutated by later pops.
Frequently asked questions
What is the difference between Combination Sum and Combination Sum II?
In the first problem candidates are distinct and each can be reused any number of times. Here each candidate is used at most once and the input can contain duplicates, so you recurse to i + 1 and must skip repeated values to avoid duplicate combinations.
How do you avoid duplicate combinations in Combination Sum II?
Sort the candidates and, when you choose not to take a value, skip all of its remaining copies. That way a group of equal values contributes each possible count only once.
Why does sorting help prune the search?
Besides grouping duplicates, sorting lets the loop-based version stop as soon as one value exceeds the remaining target, since every later value is at least as large.
What is the time complexity of Combination Sum II?
The worst case is O(n × 2^n), since each candidate is either taken or not and each result costs O(n) to copy. In practice the target bound prunes most branches.