15% off all plans & roadmaps Use code
See plansCombination Sum II
- LeetCode 40
- Medium
- Backtracking Patterns
- Combination Sum
Updated
TL;DR: Find every unique group of numbers from a list with duplicates that adds up to a target, using each position once. Sort the list, backtrack, and skip a value that repeats the previous one at the same depth.
Problem
You get an array of candidate numbers candidates and a number target. Return every unique combination of candidates whose values add up to target.
Each element of candidates can be used at most once in a combination. The array may contain duplicate values, but the answer must not contain duplicate combinations. The combinations may be returned in any order.
Example 1
Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
Example 2
Input: candidates = [2,5,2,1,2], target = 5 Output: [ [1,2,2], [5] ]
Constraints
1 <= candidates.length <= 1001 <= candidates[i] <= 501 <= target <= 30
Constraints that matter
candidates.lengthup to 100 means a full power set of 2^100 subsets is impossible, so you must prune.- Every value is at least 1, so the running sum only grows. Once it passes
target, you can stop that branch. targetis at most 30, so a combination holds at most 30 numbers. Recursion depth never exceeds 30 even with 100 candidates.- Values are small and positive, so sorting is cheap and lets you break out of a loop as soon as one value is too big.
- Duplicates are allowed in the input, so the answer needs a rule that stops two equal values from producing the same combination twice.
Hints
Hint 1
This is backtracking over a decision tree.
Hint 2
Try every subset of the array.
Solution
Intuition
This is backtracking over a decision tree. You build a combination one number at a time, and you undo the last choice when a branch is finished. Each recursive call picks the next number from the part of the array that is still available.
Picture a row of sorted coin jars where two jars hold identical coins. At each step you pick one jar to dip into, and once you have looked through a jar you never open another identical jar at that same step, because it would only show you the same handful again.
The twist is duplicates. With [1, 1, 6] and target 8, the first 1 plus 6 gives the same combination as the second 1 plus 6. If the code treats the two ones as different, the same multiset shows up twice.
Sort the array first so equal values sit side by side. At any single call, the loop should try each distinct value once as the next pick. If candidates[i] equals candidates[i-1] and i is past the first index the loop started from, the previous iteration already explored every combination that starts with that value from this position. Trying it again can only repeat work.
The check is i > start, not i > 0. A deeper call may legitimately pick the second 1 after the first 1 was already chosen higher in the tree. That is how [1, 1, 6] gets built. The skip applies to siblings in one loop, not to parent and child.
Sorting also gives a free pruning rule. If candidates[i] is bigger than the remaining target, every later value is bigger too, so you break rather than continue.
Worked example
Input: candidates = [1, 1, 1, 1], target = 4 Output: [[1, 1, 1, 1]] Explanation: All four ones are needed to reach 4, so the only valid group is [1, 1, 1, 1]. Four different positions could supply any single 1, yet the answer must list the combination once. This input is a good test of duplicate handling.
Approach 1: Brute force: all subsets plus a set
Try every subset of the array. For each one, add up the values and keep it when the sum equals target. Because the input has duplicates, the same multiset can come from different positions, so store each found combination in a set to remove repeats.
Sort the array first so that every subset is built in ascending order. Then two subsets with the same values produce the identical list, and the set can compare them directly. Stop a branch when the sum passes target, since all values are positive.
Steps
- Sort
candidatesascending. - Define
pick(i, total, path)that decides whether to takecandidates[i]. - If
total == target, recordpathwhen it is not already in the set, then return. - If
ireached the end ortotal > target, return. - Take
candidates[i]: push it, recurse withi + 1, then pop it. - Skip
candidates[i]: recurse withi + 1and the samepath. - Call
pick(0, 0, [])and return the recorded combinations.
Dry run
Take [1, 1, 1, 1] with target 4. The sort changes nothing.
- Each of the four positions is either taken or skipped, so the recursion visits subsets of every size.
- Subsets of size 0 to 3 have sums 0 to 3, all below 4, so none is recorded.
- Only the branch that takes all four ones reaches
total == 4. It records[1, 1, 1, 1]. - The set is empty at that moment, so the combination is added.
The result is [[1, 1, 1, 1]]. With only one match the set never has to reject anything here. On [1, 1, 6] with target 8 it would reject the second [1, 6] style repeat.
Complexity
| Time | O(2^n * n) |
|---|---|
| Space | O(n) recursion, plus the set of stored combinations |
Here n is the length of candidates. Each element is taken or skipped, so the recursion tree has up to 2^n leaves. Each recorded hit costs O(n) to copy and to hash or compare. The recursion depth is n, and the set holds only the unique answers, which are part of the output.
PythonTested in our runner
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
seen = set()
result = []
def pick(i, total, path):
if total == target:
key = tuple(path)
if key not in seen:
seen.add(key)
result.append(list(path))
return
if i == len(candidates) or total > target:
return
# take candidates[i]
path.append(candidates[i])
pick(i + 1, total + candidates[i], path)
path.pop()
# skip candidates[i]
pick(i + 1, total, path)
pick(0, 0, [])
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
Set<String> seen = new HashSet<>();
List<int[]> result = new ArrayList<>();
pick(candidates, target, 0, 0, new ArrayList<>(), seen, result);
return result.toArray(new int[0][]);
}
private void pick(int[] c, int target, int i, int total, List<Integer> path,
Set<String> seen, List<int[]> result) {
if (total == target) {
if (seen.add(path.toString())) {
int[] copy = new int[path.size()];
for (int k = 0; k < copy.length; k++) copy[k] = path.get(k);
result.add(copy);
}
return;
}
if (i == c.length || total > target) return;
path.add(c[i]);
pick(c, target, i + 1, total + c[i], path, seen, result);
path.remove(path.size() - 1);
pick(c, target, i + 1, total, path, seen, result);
}
}
C++Tested in our runner
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
set<vector<int>> seen;
vector<vector<int>> result;
vector<int> path;
pick(candidates, target, 0, 0, path, seen, result);
return result;
}
private:
void pick(vector<int>& c, int target, int i, int total, vector<int>& path,
set<vector<int>>& seen, vector<vector<int>>& result) {
if (total == target) {
if (seen.insert(path).second) result.push_back(path);
return;
}
if (i == (int)c.size() || total > target) return;
path.push_back(c[i]);
pick(c, target, i + 1, total + c[i], path, seen, result);
path.pop_back();
pick(c, target, i + 1, total, path, seen, result);
}
};
JavaScriptTested in our runner
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
candidates.sort((a, b) => a - b);
const seen = new Set();
const result = [];
const path = [];
const pick = (i, total) => {
if (total === target) {
const key = path.join(',');
if (!seen.has(key)) {
seen.add(key);
result.push([...path]);
}
return;
}
if (i === candidates.length || total > target) return;
path.push(candidates[i]);
pick(i + 1, total + candidates[i]);
path.pop();
pick(i + 1, total);
};
pick(0, 0);
return result;
};
GoTested in our runner
import (
"fmt"
"sort"
)
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
seen := map[string]bool{}
result := [][]int{}
path := []int{}
var pick func(i, total int)
pick = func(i, total int) {
if total == target {
key := fmt.Sprint(path)
if !seen[key] {
seen[key] = true
result = append(result, append([]int(nil), path...))
}
return
}
if i == len(candidates) || total > target {
return
}
path = append(path, candidates[i])
pick(i+1, total+candidates[i])
path = path[:len(path)-1]
pick(i+1, total)
}
pick(0, 0)
return result
}
C#Tested in our runner
public class Solution {
public int[][] combinationSum2(int[] candidates, int target) {
Array.Sort(candidates);
var seen = new HashSet<string>();
var result = new List<int[]>();
Pick(candidates, target, 0, 0, new List<int>(), seen, result);
return result.ToArray();
}
private void Pick(int[] c, int target, int i, int total, List<int> path,
HashSet<string> seen, List<int[]> result) {
if (total == target) {
if (seen.Add(string.Join(",", path))) {
result.Add(path.ToArray());
}
return;
}
if (i == c.Length || total > target) return;
path.Add(c[i]);
Pick(c, target, i + 1, total + c[i], path, seen, result);
path.RemoveAt(path.Count - 1);
Pick(c, target, i + 1, total, path, seen, result);
}
}

Solution pattern
Combination Sum
Part of Backtracking Patterns
Approach 2: Sorted backtracking with sibling skipOptimalCombination Sum
What's slow: the brute force builds every duplicate combination and only throws it away at the end. With many equal values it explores the same subtree again and again. It also keeps walking down a branch after the remaining target has dropped below every available number.
The insight that fixes it: sort, and let each call loop over the next pick. The loop moves forward from start, so each element is used once and order inside a combination never varies.
If i > start and candidates[i] == candidates[i-1], skip. The earlier sibling already covered every combination that begins with that value here. Break out of the loop when candidates[i] > remaining, since later values are at least as large. Duplicates are never generated, so no set is needed.
Why it is correct. At each call, the loop tries every distinct value once as the next pick, so every multiset that starts from this position is reached. When candidates[i] equals candidates[i-1] and i is past start, the earlier sibling already explored all combinations beginning with that value here. Skipping the repeat therefore loses nothing and only removes duplicate work.
Steps
- Sort
candidatesascending. - Define
dfs(start, remaining)with a sharedpathlist. - If
remaining == 0, copypathinto the result and return. - Loop
ifromstartto the end of the array. - If
candidates[i] > remaining, break, because the array is sorted. - If
i > startandcandidates[i] == candidates[i-1], continue to skip the repeated sibling. - Push
candidates[i], calldfs(i + 1, remaining - candidates[i]), then pop it.
Dry run
Trace [1, 1, 1, 1] with target 4. The final frame in the table shows the combination being recorded, and every other row shows a skip or a return.
| Step | Call (start, remaining) | Loop i | Action | Path |
|---|---|---|---|---|
| 1 | dfs(0, 4) | 0 | pick 1, go deeper | [1] |
| 2 | dfs(1, 3) | 1 | pick 1, go deeper | [1,1] |
| 3 | dfs(2, 2) | 2 | pick 1, go deeper | [1,1,1] |
| 4 | dfs(3, 1) | 3 | pick 1, go deeper | [1,1,1,1] |
| 5 | dfs(4, 0) | none | remaining is 0, record a copy | [1,1,1,1] |
| 6 | back in dfs(3, 1) | 4 | loop ends, pop | [1,1,1] |
| 7 | back in dfs(2, 2) | 3 | 3 > start 2 and equals previous, skip | [1,1,1] |
| 8 | back in dfs(1, 3) | 2, 3 | both skipped, pop | [1] |
| 9 | back in dfs(0, 4) | 1, 2, 3 | all skipped, pop | [] |
The result is [[1, 1, 1, 1]], recorded once. The brute force touched all 16 subsets. This version makes 5 calls and skips the rest in a handful of checks.
Complexity
| Time | O(2^n) worst case, with a per-answer copy cost |
|---|---|
| Space | O(min(n, target)) for the path and recursion, excluding the output |
Here n is the length of candidates. Sorting costs O(n log n). The recursion tree has at most one node per distinct sub-multiset whose sum stays within target, and that count is bounded by the 2^n subsets.
Each recorded answer costs O(length) to copy. The path holds at most min(n, target) numbers. Every value is at least 1 and the remaining target must stay non-negative.
PythonTested in our runner
from typing import List
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
result = []
path = []
def dfs(start, remaining):
if remaining == 0:
result.append(list(path))
return
for i in range(start, len(candidates)):
# sorted, so every later value is too big as well
if candidates[i] > remaining:
break
# skip a repeated value among siblings at this depth
if i > start and candidates[i] == candidates[i - 1]:
continue
path.append(candidates[i])
dfs(i + 1, remaining - candidates[i])
path.pop()
dfs(0, target)
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<int[]> result = new ArrayList<>();
dfs(candidates, 0, target, new ArrayList<>(), result);
return result.toArray(new int[0][]);
}
private void dfs(int[] c, int start, int remaining, List<Integer> path, List<int[]> result) {
if (remaining == 0) {
int[] copy = new int[path.size()];
for (int k = 0; k < copy.length; k++) copy[k] = path.get(k);
result.add(copy);
return;
}
for (int i = start; i < c.length; i++) {
if (c[i] > remaining) break;
if (i > start && c[i] == c[i - 1]) continue;
path.add(c[i]);
dfs(c, i + 1, remaining - c[i], path, result);
path.remove(path.size() - 1);
}
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> result;
vector<int> path;
dfs(candidates, 0, target, path, result);
return result;
}
private:
void dfs(vector<int>& c, int start, int remaining, vector<int>& path,
vector<vector<int>>& result) {
if (remaining == 0) {
result.push_back(path);
return;
}
for (int i = start; i < (int)c.size(); i++) {
if (c[i] > remaining) break;
if (i > start && c[i] == c[i - 1]) continue;
path.push_back(c[i]);
dfs(c, i + 1, remaining - c[i], path, result);
path.pop_back();
}
}
};
JavaScriptTested in our runner
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
candidates.sort((a, b) => a - b);
const result = [];
const path = [];
const dfs = (start, remaining) => {
if (remaining === 0) {
result.push([...path]);
return;
}
for (let i = start; i < candidates.length; i++) {
if (candidates[i] > remaining) break;
if (i > start && candidates[i] === candidates[i - 1]) continue;
path.push(candidates[i]);
dfs(i + 1, remaining - candidates[i]);
path.pop();
}
};
dfs(0, target);
return result;
};
GoTested in our runner
import "sort"
func combinationSum2(candidates []int, target int) [][]int {
sort.Ints(candidates)
result := [][]int{}
path := []int{}
var dfs func(start, remaining int)
dfs = func(start, remaining int) {
if remaining == 0 {
result = append(result, append([]int(nil), path...))
return
}
for i := start; i < len(candidates); i++ {
if candidates[i] > remaining {
break
}
if i > start && candidates[i] == candidates[i-1] {
continue
}
path = append(path, candidates[i])
dfs(i+1, remaining-candidates[i])
path = path[:len(path)-1]
}
}
dfs(0, target)
return result
}
C#Tested in our runner
public class Solution {
public int[][] combinationSum2(int[] candidates, int target) {
Array.Sort(candidates);
var result = new List<int[]>();
Dfs(candidates, 0, target, new List<int>(), result);
return result.ToArray();
}
private void Dfs(int[] c, int start, int remaining, List<int> path, List<int[]> result) {
if (remaining == 0) {
result.Add(path.ToArray());
return;
}
for (int i = start; i < c.Length; i++) {
if (c[i] > remaining) break;
if (i > start && c[i] == c[i - 1]) continue;
path.Add(c[i]);
Dfs(c, i + 1, remaining - c[i], path, result);
path.RemoveAt(path.Count - 1);
}
}
}
Common mistakes
- Writing
if i > 0 and candidates[i] == candidates[i-1]: continueinstead ofi > start. This forbids using two equal values together, so[1, 1, 6]is lost. Compare againststart, not 0. - Skipping duplicates without sorting first. Equal values are not adjacent, so
candidates[i] == candidates[i-1]misses repeats. Callsortbefore the firstdfs. - Recursing with
dfs(i, ...)instead ofdfs(i + 1, ...). That is the Combination Sum I rule and lets one element be reused. Passi + 1. - Appending
pathdirectly withresult.append(path). The list is mutated later and every stored answer ends up empty. Append a copy such aslist(path). - Using
continuewhere the too-big check needsbreak. It still returns the right answer but scans every remaining value in every call. Break, because the array is sorted. - Checking
remaining == 0only after the loop starts, or never returning after recording. Return as soon asremaining == 0so you do not try to add more numbers to a finished combination.
Edge cases
candidates = [1],target = 1returns[[1]], the smallest valid input.candidates = [2],target = 1returns an empty list because no combination reaches the target.candidates = [1, 1, 1, 1],target = 4returns one combination,[[1, 1, 1, 1]], not four copies.candidates = [2, 5, 2, 1, 2],target = 5returns[1, 2, 2]and[5]. Three equal 2s must not make[2, 2, 1]appear in more than one form.candidates = [1, 2, 3],target = 30returns an empty list. The sum of all values is 6, so every branch dies.- One hundred ones with
target = 30has a single answer with thirty ones. The skip rule keeps the search small, while the brute force would blow up here.
Follow-ups interviewers ask
- What changes if each number may be used any number of times, as in Combination Sum I?
- Recurse with
dfs(i, ...)so the same index can be picked again. If the input has no duplicates you need no skip rule. If it does have duplicates, dedupe the array first, or keep the skip check. - How would you do this without relying on the skip check, for example by counting values?
- Sort, then build a list of (value, count) pairs. At each pair, choose how many copies to take, from 0 up to its count, and move to the next pair. Every combination is a unique choice of counts, so duplicates cannot occur.
- Can you cut work further for large inputs?
- Yes. Precompute suffix sums and return early if the remaining numbers cannot reach the remaining target. You can also stop when the smallest remaining value exceeds the target. Neither changes the worst-case bound, but both trim real runs.
Combination Sum II FAQ
What is the time complexity of Combination Sum II?
The bound you can prove is O(2^n), where n is the number of candidates, plus the cost of copying each answer. Sorting adds O(n log n). In practice pruning on the remaining target and skipping repeated siblings make it far smaller. Since target is at most 30, each path has at most 30 numbers.
Why use backtracking for Combination Sum II?
You must list every valid combination, not count them or find one. That forces you to explore choices and undo them. Backtracking builds one combination in a shared list and reverts the last pick when a branch ends, which keeps memory small and lets you prune early.
Why sort the array first in LeetCode 40?
Sorting puts equal values next to each other, so comparing candidates[i] with candidates[i-1] detects a repeat. It also lets you break out of the loop as soon as a value is greater than the remaining target.
Why is the skip condition i > start and not i > 0?
The check should only skip a repeat among siblings in one loop. A deeper call starts at start = i + 1, so its first element is allowed even if it equals the value picked above. Using i > 0 would block [1, 1, 6].
Can Combination Sum II be solved in O(1) extra space?
No. The recursion stack and the current path grow with the number of picked values, up to min(n, target). You can drop the set used in the brute force, but you cannot remove the path and the stack.
How is Combination Sum II different from Combination Sum I?
In Combination Sum I every number can be reused and the input has distinct values. Here each element is used once and the input can repeat values. So you recurse on i + 1 instead of i, and you add the sibling skip rule to avoid duplicate combinations.
Asked at
See which companies ask this — Pro
Related problems
- Combination Sum · same technique: Combination Sum
- Partition to K Equal Sum Subsets · same technique: Combination Sum
- N-Queens · next harder, same pattern
- Word Search · same pattern: Backtracking Patterns
- Subsets · same pattern: Backtracking Patterns
- Permutations · same pattern: Backtracking Patterns
- Letter Combinations of a Phone Number · same pattern: Backtracking Patterns
- Generate Parentheses · same pattern: Backtracking Patterns
- Palindrome Partitioning · same pattern: Backtracking Patterns
- Subsets II · same pattern: Backtracking Patterns