Backtracking: subsets, permutations, combinations
Generate subsets, permutations and combinations with a choose-explore-unchoose template.
By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.
In short
Backtracking builds candidate solutions one choice at a time and undoes the last choice when it leads nowhere. It systematically explores a tree of decisions, generating subsets, permutations and combinations. The choose, explore, unchoose template fits almost every problem in this family.
Explained simply
Imagine trying every outfit you could make from your clothes. You pick a shirt, then trousers, then shoes. After you look at one outfit, you take the shoes off and try other shoes. When all shoes are tried, you change the trousers. That habit of trying, undoing and trying the next thing is backtracking.
In code, backtracking builds an answer one choice at a time. The choices made so far are called the path. When the path is complete, you save a copy of it. Then you undo the last choice and try the next option at that step.
The same pattern answers many "list them all" questions: every subset of a set, every ordering of some items (a permutation), every group of k items (a combination), or every way to reach a target sum.
These answers can be huge in number. A set of 20 items has over a million subsets, and 10 items can be ordered in over 3.6 million ways. So backtracking is for small inputs, and its main skill is not wasting time on paths that cannot work.
Press Play on a diagram to walk through it one step at a time.
- Take 1: [1]
- Take 2: [1, 2]
- Skip 2: [1]
- Skip 1: []
- Take 2: [2]
- Skip 2: []
- 1Choose
path.append(option)
- 2Explore
Recurse to the next step.
- 3Unchoose
path.pop() restores the state.
- 4Next option
Loop to the next candidate.
- Back to step 1
- 1 first
- [1, 2, 3]
- [1, 3, 2]
- 2 first
- [2, 1, 3]
- [2, 3, 1]
- 3 first
- [3, 1, 2]
- [3, 2, 1]
In depth
One template, three shapes
Every backtracking function has the same skeleton: if the path is complete, record a copy; otherwise loop over the options for the next step, and for each one choose it (append to path), explore (recurse), and unchoose (pop). What changes between problems is what counts as an option.
For subsets and combinations, order does not matter, so you pass a start index and only consider items after the last one picked. That stops [1, 2] and [2, 1] both appearing. For permutations, order matters, so every unused item is an option at every step, and a used list (or set) remembers what is already in the path.
Recording happens at different moments too: subsets record at every node of the tree, combinations only when the path has k items, permutations only when it has n items.
- Options: items after start
- Record at every call
- 2^n results
- Options: items after start
- Record when len(path) == k
- C(n, k) results
- Options: any unused item
- Record when len(path) == n
- n! results
How much work is it really?
The run time is roughly the number of results times the cost to copy each one. Subsets: 2^n results, each copied in O(n), so O(n x 2^n). Permutations: n! results, so O(n x n!). Combinations of k: C(n, k) results, each of length k, so O(k x C(n, k)).
Those numbers grow terrifyingly fast. 2^20 = 1,048,576 subsets is fine in Python. 2^30 is about a billion, which is not. 10! = 3,628,800 permutations takes a few seconds; 12! = 479,001,600 is far too many. So when a problem says n <= 15 or n <= 20, that is a strong hint that exponential search is the intended solution.
The recursion depth equals the path length, at most n, so Python's recursion limit is rarely a problem here.
- n <= 20: 2^n search is fine
- n <= 10: n! search is fine
- Depth = length of the path
Skipping duplicate answers
With input [1, 2, 2], picking "the first 2" or "the second 2" gives the same subset, so naive code prints duplicates. The fix has two parts. First, sort the input so equal values sit next to each other. Second, at one level of the loop, skip a value equal to the one just tried: if i > start and nums[i] == nums[i - 1], continue. You may still use both 2s in one path (going deeper), but you never start the same branch twice at the same depth.
For permutations with duplicates, the rule is: skip nums[i] if it equals nums[i - 1] and nums[i - 1] is not currently used. This forces equal values to be placed in their original order, so each distinct ordering appears once.
- Pick 1
- [1, 2]
- [1, 2, 2]
- Pick first 2
- [2, 2]
- Pick second 2
- Skipped: same value as the 2 just tried
Combination sum and pruning by order
Combination sum asks for every list of candidates (each usable many times) that adds up to a target. Reuse is a one-character change: recurse with i instead of i + 1, so the same item can be picked again but earlier items cannot come back.
Sorting helps a second time here. If the candidates are sorted and candidates[i] is already bigger than the remaining amount, every later candidate is bigger too, so you can break out of the loop instead of just skipping one item. This simple prune often cuts the search by a large factor.
If each candidate may be used only once and the input has duplicates (combination sum II), combine both rules: recurse with i + 1 and skip equal neighbours at the same depth.
- Reuse allowed: recurse with i
- Use once: recurse with i + 1
- Sorted input: break when the item exceeds what is left
Backtracking in real Python code
For plain generation, the standard library already does the job in fast C code: itertools.combinations(items, k), itertools.permutations(items), and itertools.product(options, repeat=n). Subsets can be built by chaining combinations for every size.
Write your own backtracking when you need rules applied during generation, such as "the sum may not exceed the target" or "no two neighbours may be equal". Filtering itertools output after the fact visits every candidate, while a hand-written search can cut a branch the moment it breaks a rule.
Two habits prevent most bugs. Append path[:] (a copy), never path itself, because the list keeps changing. And undo exactly what you did, in reverse order, right after the recursive call.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Learn the choose, explore, unchoose template~40m
- 2Generate all subsets~40m
- 3Generate all permutations~40m
- 4Generate combinations and combination sums~40m
- 5Skip duplicates in sorted input~40m
Key points
- Subsets: O(n x 2^n); permutations: O(n x n!).
- Copy the current path when recording it, otherwise later changes alter it.
- Sort input and skip equal neighbours to avoid duplicate results.
- Recursion depth equals the number of choices, usually n.
Key terms
Tap a card to flip it. 0/3 known
Examples
def subsets(nums): # O(n * 2^n)
out, path = [], []
def go(i):
if i == len(nums):
out.append(path[:]) # copy
return
path.append(nums[i]); go(i + 1) # choose, explore
path.pop(); go(i + 1) # unchoose, skip
go(0)
return out
def permutations(nums): # O(n * n!)
if not nums: return [[]]
return [[x] + p for i, x in enumerate(nums)
for p in permutations(nums[:i] + nums[i + 1:])]Combination sum
Candidates [2, 3, 6, 7], target 7, each candidate usable many times. Step 1: sort. Step 2: from the start index, try each candidate; if it is larger than what remains, stop the loop. Step 3: recurse with the same index so it can be reused. Trace: 2, 2, 2 leaves 1, and 2 > 1, so back up; 2, 2, 3 hits 0, record it; 7 alone hits 0, record it. The answer is [[2, 2, 3], [7]].
def combination_sum(cands, target):
cands.sort()
out, path = [], []
def go(start, remain):
if remain == 0:
out.append(path[:]); return
for i in range(start, len(cands)):
if cands[i] > remain: break # sorted: the rest are bigger too
path.append(cands[i])
go(i, remain - cands[i]) # i, not i + 1: reuse allowed
path.pop()
go(0, target)
return out
print(combination_sum([2, 3, 6, 7], 7)) # [[2, 2, 3], [7]]Subsets without duplicates
Input [2, 1, 2]. Sorting gives [1, 2, 2]. This version records the path at every call, which lists every subset exactly once. The skip rule i > start and nums[i] == nums[i - 1] stops the second 2 from starting a branch the first 2 already started at the same depth. Result: [], [1], [1, 2], [1, 2, 2], [2], [2, 2], which is 6 subsets instead of 8.
def subsets_with_dup(nums):
nums.sort()
out, path = [], []
def go(start):
out.append(path[:]) # every node is a subset
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue # same value at the same depth
path.append(nums[i]); go(i + 1); path.pop()
go(0)
return out
print(subsets_with_dup([2, 1, 2]))
# [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]Quick reference
- Template: if done, record path[:]; else for each option: choose, recurse, unchoose
- Subsets O(n x 2^n), permutations O(n x n!), combinations O(k x C(n, k))
- Order does not matter: pass a start index; order matters: keep a used list
- Duplicates: sort, then skip if i > start and nums[i] == nums[i - 1]
- Reuse allowed: recurse with i; use once: recurse with i + 1
- Sorted candidates: break (not continue) when one is larger than what remains
- itertools.combinations, permutations and product cover plain generation
- n <= 20 in the constraints often signals exponential search
Common mistakes
- Appending path instead of path[:] to the results.
- Forgetting to undo state after the recursive call.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write combine(n, k) that returns every combination of k numbers from 1 to n. Example: combine(4, 2) has 6 lists.
- Exercise 2medium
Return all distinct permutations of a list that may contain duplicates. Example: [1, 1, 2] gives 3 permutations.
- Exercise 3hard
Return every way to split a string into pieces that are all palindromes. Example: "aab" gives [["a", "a", "b"], ["aa", "b"]].
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between backtracking and recursion?
- Recursion is the tool: a function calling itself. Backtracking is a strategy that uses recursion to build choices step by step and undo them to try alternatives.
- Is backtracking the same as DFS?
- Backtracking is a depth-first search over the tree of choices. The difference is mostly in wording: DFS usually walks an existing graph, while backtracking builds the tree as it goes and prunes it.
- When should I use itertools instead of writing backtracking?
- Use itertools when you need every combination or permutation with no extra rules. Write backtracking when rules can cut branches early, because filtering itertools output still visits every candidate.