Combinations
medium 20 minCombination problems pick items where order does not matter.
Video lesson · Chapter 1 of 9
Balance the sample crate
Combinations in 75 seconds
1:26Reel
How it works
Step through the idea, or press Play.
Look forward only. Each call picks from a start index onwards, so a set is built in one order and never repeated
Understand it
Start here
Recap: backtracking with a start index
You already know the rhythm
Choose, explore, unchoose, from Backtracking. This page only changes which options each call may choose from and when it stops.
Subsets are the parent
The start-index loop from Subsets saves every node. Combinations save only the nodes that meet a rule: length , or a total equal to the target.
Counting is a separate topic
Why there are ways to choose is covered in Combinations vs permutations. Here we list them in code.
A combination is a selection where order does not matter: {2, 3} and {3, 2} are the same team, the same basket, the same answer. A permutation cares about order, which is why Permutations uses a used array instead of a start index.
The count
How many answers: C(n, k)
Choose k of n
The output-size bound
| n | k | Feels like | |
|---|---|---|---|
| 4 | 2 | 6 | instant |
| 10 | 5 | 252 | instant |
| 20 | 10 | 184,756 | fine |
| 30 | 15 | 155,117,520 | too many to list |
Pattern 1
Choose k of n
Build the combination in increasing order. Each call has a start value and may only pick numbers from there upwards, so [2, 1] is never built as a copy of [1, 2]. When the path holds numbers, save a copy and return: answers live only at depth .
One call of backtrack(start)
start and never goes past the last value that still leaves room for the rest of the combination.def combine(n, k): result, path = [], [] def backtrack(start): if len(path) == k: result.append(path[:]) # depth k: one combination return need = k - len(path) for i in range(start, n - need + 2): # leave room for the rest path.append(i) # choose backtrack(i + 1) # explore: only bigger numbers path.pop() # unchoose backtrack(1) return resultprint(combine(4, 2)) # [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]print(len(combine(10, 5))) # 252Pruning
Stop when not enough items remain
The last useful start
range excludes its end, so the loop is range(start, n - need + 2).combine(4, 2) with the bound
[4] would need one more number bigger than 4, so the bound removes it before the call is made.Pattern 2
Combination Sum: reuse allowed
Given distinct positive candidates and a target, list every combination that adds up to the target, using any candidate as often as you like. Two changes from k of n: the base case is total == target, and the call passes i instead of i + 1, so the same candidate stays available. Sort first, and when total + candidates[i] > target you can break: every later candidate is at least as big.
combination_sum([2, 3, 6, 7], 7)
[2,2,3] and [7].def combination_sum(candidates, target): candidates = sorted(candidates) # sorted: one overshoot ends the loop result, path = [], [] def backtrack(start, total): if total == target: result.append(path[:]) return for i in range(start, len(candidates)): if total + candidates[i] > target: break # every later candidate is bigger path.append(candidates[i]) backtrack(i, total + candidates[i]) # i, not i + 1: reuse allowed path.pop() backtrack(0, 0) return resultprint(combination_sum([2, 3, 6, 7], 7)) # [[2, 2, 3], [7]]print(combination_sum([2, 3, 5], 8)) # [[2, 2, 2, 2], [2, 3, 3], [3, 5]]print(combination_sum([1, 2], 4)) # [[1, 1, 1, 1], [1, 1, 2], [2, 2]]How deep can it go?
One character
i or i + 1
backtrack(i, ...): reuse allowed
- Combination Sum: the same candidate may appear many times, e.g. [2, 2, 2].
- Depth is bounded by the target, not by n.
- [2, 3, 5] to 8 gives [2,2,2,2], [2,3,3] and [3,5].
backtrack(i + 1, ...): each once
- Combination Sum II and III, k of n: every item is used at most once.
- Depth is at most n, so the tree is at most the 2ⁿ subsets.
- [2, 3, 5] to 8 gives only [3,5].
| Problem | Recurse with | Stop when | Extra prune |
|---|---|---|---|
| Combinations, k of n | i + 1 | len(path) == k | i <= n - need + 1 |
| Combination Sum | i | total == target | sorted, break on overshoot |
| Combination Sum II | i + 1 | total == target | skip equal neighbour at the same level |
| Combination Sum III | i + 1 (digits 1 to 9) | len(path) == k | break when the digit exceeds what remains |
| Phone letters | index + 1 | index == len(digits) | none: every leaf is an answer |
Pattern 3
Combination Sum II: duplicates in the input
Now each item may be used once, but the input can repeat values, as in [10, 1, 2, 7, 6, 1, 5]. Picking the first 1 or the second 1 builds the same combinations, so the output would contain duplicates. Sort to put equal values side by side, then in the loop skip a value equal to the one before it at the same level.
The loop body in Combination Sum II
[1, 2, 2, 3] with target 5 the skip fires twice: once for the second 2 under [1] and once at the root. The answers are [1,2,2] and [2,3], each once.def combination_sum2(candidates, target): candidates = sorted(candidates) # equal values side by side result, path = [], [] def backtrack(start, total): if total == target: result.append(path[:]) return for i in range(start, len(candidates)): if i > start and candidates[i] == candidates[i - 1]: continue # same value already tried at this level if total + candidates[i] > target: break path.append(candidates[i]) backtrack(i + 1, total + candidates[i]) # each item once path.pop() backtrack(0, 0) return resultprint(combination_sum2([10, 1, 2, 7, 6, 1, 5], 8)) # [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]print(combination_sum2([2, 1, 3, 2], 5)) # [[1, 2, 2], [2, 3]]Pattern 4
Combination Sum III: k digits from 1 to 9
Find every set of different digits from 1 to 9 that adds up to . It is k of n and Combination Sum at once: the candidates are the digits 1 to 9, each used once (d + 1), and the base case checks both the length and the total. The digits are already sorted, so a digit bigger than what remains breaks the loop.
Reject impossible targets before searching
def combination_sum3(k, n): if not (k * (k + 1) // 2 <= n <= k * (19 - k) // 2): return [] # impossible target result, path = [], [] def backtrack(start, remaining): if len(path) == k: if remaining == 0: result.append(path[:]) return for d in range(start, 10): if d > remaining: break # digits only get bigger path.append(d) backtrack(d + 1, remaining - d) # each digit once path.pop() backtrack(1, n) return resultprint(combination_sum3(3, 7)) # [[1, 2, 4]]print(combination_sum3(3, 9)) # [[1, 2, 6], [1, 3, 5], [2, 3, 4]]print(combination_sum3(4, 30)) # [[6, 7, 8, 9]]: 9 + 8 + 7 + 6 is the largest sumprint(combination_sum3(4, 31)) # []: rejected before any callPattern 5
Letter combinations of a phone number
Each keypad digit maps to 3 or 4 letters; list every string made by picking one letter per digit. This is the one combination pattern with no start index: each level draws from a different digit's letters, so the index into the digit string is the depth, and nothing can repeat.
"23": one level per digit
A product of choices
PHONE = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}def letter_combinations(digits): if not digits: return [] result, path = [], [] def backtrack(index): if index == len(digits): result.append("".join(path)) return for ch in PHONE[digits[index]]: path.append(ch) backtrack(index + 1) path.pop() backtrack(0) return resultprint(letter_combinations("23")) # ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']print(len(letter_combinations("79"))) # 16Complexity
What each variant costs
| Problem | Time | Space (path + stack) | Why |
|---|---|---|---|
| k of n | answers, each copied in | ||
| Combination Sum | worst case | Up to choices on each of levels | |
| Combination Sum II | Each item in or out once; sorting adds | ||
| Combination Sum III | At most 126 digit sets | ||
| Phone letters | Up to 4 letters per digit |
Choosing
Which template is it?
- 1Sortcandidates ascending
- 2Prunesum + c[i] > target: break
- 3Explorerecurse with i or i + 1
- 4Checksum == target: save
Sort once, then every call loops through prune, explore and check. The loop arrow is the for-loop moving to the next candidate.
Pick the variant from the problem statement
The same skip elsewhere
Subsets II and Permutations II use the identical line: sort, then skip a value equal to its left neighbour at the same level.
Combination Sum IV is DP
It counts ordered sequences, so
[1, 2]and[2, 1]are different. That is a counting problem: use dynamic programming from DP core, not backtracking.itertools.combinations
Python's library lists k of n in the same order as our template. Use it in real code; write the backtracking in interviews.
Recap
Key takeaways
Key points
- A combination ignores order, so build it in index order with a start index; that alone removes reordered duplicates.
- k of n stops at depth k and loops only up to n - need + 1, so every branch can still be completed.
- There are C(n, k) answers, so listing them costs at least O(k · C(n, k)).
- Combination Sum recurses with i (reuse); Combination Sum II and III recurse with i + 1 (each once).
- Sort, then break on the first overshoot; that is only safe with sorted, non-negative numbers.
- Duplicates: skip c[i] when i > start and c[i] == c[i - 1]. Same value across one level is a duplicate; down the tree it is fine.
- Phone letters have no start index: the digit index is the depth and every leaf is an answer.
- Save path[:], and when only a count is asked, reach for the formula or DP instead.