Kodewick
Start learning →
Backtracking48 / 52

Backtracking

Lesson 48 of 52 · Part 9 · Algorithm design · about 22 minutes

Backtracking tries every possibility in an orderly way: make a choice with path.append, go deeper with a recursive call, then undo it with path.pop(); record each result as a copy, and prune dead ends early.

A 4-digit combination lock opens in 10⁴ = 10000 ways; 10 people stand in a queue in 10! = 3628800 orders; picking some of 20 things can be done in 2²⁰ = 1048576 ways. For problems like "list every possibility" or "find every combination that fits", there is no clever shortcut, only trying them one by one, but in an orderly way: at each step make a choice and go deeper; at the end, record the result, then undo the choice and try the next. That is backtracking. It comes up a lot in interviews (permutations, subsets, combination sum, N-queens, generating brackets), and the code almost always has the same shape. This lesson makes that shape second nature, then looks at the two things that really decide right and wrong, fast and slow: copying when you record a result, and cutting off dead ends early.

Choose, explore, un-choose

Find every permutation of [1, 2, 3]. Think of it as filling 3 blanks: the first can be 1, 2 or 3; once it is 1, the second can only be 2 or 3… Each choice is an edge going down the tree, and each path from the root to a leaf is one permutation.

[ ]
1def go():2    if len(path) == len(nums):      # at a leaf: record an answer3        res.append(path[:])4        return5    for i, x in enumerate(nums):6        if used[i]:7            continue8        used[i] = True              # choose9        path.append(x)10        go()                        # explore11        path.pop()                  # un-choose12        used[i] = False

The permutations of [1, 2, 3]: each level fills one place, and a number used cannot be chosen again. Going down is choosing, coming back is undoing; 6 leaves, 6 permutations

The code is this tree's preorder walk. path holds the choices made "from the root down to this node", and used[i] says whether number i is taken:

main.py
1def permute(nums):2    res, path = [], []3    used = [False] * len(nums)4 5    def go():6        if len(path) == len(nums):      # at a leaf: record an answer7            res.append(path[:])8            return9        for i, x in enumerate(nums):10            if used[i]:11                continue12            used[i] = True              # choose13            path.append(x)14            go()                        # explore15            path.pop()                  # un-choose16            used[i] = False17 18    go()19    return res20 21print(permute([1, 2, 3]))22print(len(permute([1, 2, 3, 4])), len(permute([1, 2, 3, 4, 5])))
Output
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
24 120

Remember the shape: path.append → recursive call → path.pop(). Whatever was chosen is undone on the way back, line for line. After the undo, path is exactly as it was before the choice, so the next turn of the loop tries the next number on a clean slate. Every backtracking problem only changes two things: when to record an answer, and what can be chosen at each step.

Choose one

Finding the permutations of 1 2 3 in the order of this decision tree (depth first, smaller numbers first at each level), which permutation is found 4th?

Choose one

After recording 1 2 3, which is the next new node the backtracking reaches?

Put in orderDrag, or use the arrows

Put these 5 lines of "choose, go down, undo" in order so the program prints the 6 permutations of [1, 2, 3].

  1. used[i] = True
  2. path.pop()
  3. used[i] = False
  4. path.append(x)
  5. go()
Should print
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Copy the path

In the previous stage the answer is recorded with res.append(path[:]), not res.append(path). What happens without the [:]? Guess first:

Guess the outputA wrong guess is fine

The permutations of [1, 2], recorded with res.append(path) and no copy. What does it print?

1res, path = [], []2used = [False, False]3 4def go():5    if len(path) == 2:6        res.append(path)7        return8    for i, x in enumerate([1, 2]):9        if not used[i]:10            used[i] = True11            path.append(x)12            go()13            path.pop()14            used[i] = False15 16go()17print(res)

It is the rule from chapter 1's "Names and objects" lesson: append stores a reference. From start to finish the search has only one path object:

Names

path
res[0]
res[1]

Objects

[]list

res.append(path) stores the path object itself; when the search ends path has been undone to empty, and every slot of res points at it

path[:], list(path) and path.copy() all work. A copy costs O(n), and it is made only when an answer is recorded, not at every step. Another way is to pass path down as an argument, go(path + [x]): each level makes a new list, so there is nothing to undo and this bug cannot happen, at the cost of copying at every step.

Choose allPick all that apply

When recording an answer, which ways correctly save "path as it is right now"? (You can pick more than one.)

Subsets and combinations

Subsets: [1, 2, 3] has 2³ = 8 subsets. To avoid repeats ({1, 2} and {2, 1} are the same), only choose later items: go(start) can only pick from index start onwards. Then every node of the tree is a subset, not just the leaves.

[ ]

The subsets of [1, 2, 3]: choosing only later items, so 1 never comes after 2; every node is an answer, numbered below in the preorder they are recorded

Combinations: choosing k of n is just the subsets of length k: record and return when the length reaches k.

main.py
1def subsets(nums):2    res, path = [], []3 4    def go(start):5        res.append(path[:])              # every node is a subset6        for j in range(start, len(nums)):7            path.append(nums[j])8            go(j + 1)                    # only later items9            path.pop()10 11    go(0)12    return res13 14def combine(nums, k):15    res, path = [], []16 17    def go(start):18        if len(path) == k:               # k chosen19            res.append(path[:])20            return21        for j in range(start, len(nums)):22            path.append(nums[j])23            go(j + 1)24            path.pop()25 26    go(0)27    return res28 29print(subsets([1, 2, 3]))30print(combine([1, 2, 3, 4], 2))31print(len(subsets(list(range(10)))), len(combine(list(range(10)), 3)))
Output
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
1024 120

The three problems have different trees and different numbers of answers:

ProblemWhat each step can chooseWhen to recordAnswers
Permutationsanything not used yetwhen all n are chosenn!
Subsetsitems from index start onat every node2ⁿ
Combinations (k of n)items from index start onwhen k are chosenC(n, k)

Backtracking takes at least the number of answers times the O(n) copy of each one: 3.6 million permutations for n = 10, over a million subsets for n = 20. It only suits problems with small n, and a problem that says n ≤ 10 or n ≤ 20 is hinting at it.

Choose one

How many subsets do 5 numbers have? And how many ways are there to pick 2 of them?

Choose one

subsets([1, 2, 3]) records the subsets in preorder. Which one is recorded fifth?

Exercise 1

Your own combinations

Complete combine(n, k): return every way of choosing k numbers from 1..n, each in increasing order, the whole list in lexicographic order, the same as itertools.combinations (turned into lists).

It should print
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
20
True
exercise1.py
1from itertools import combinations2 3def combine(n, k):4    res, path = [], []5 6    def go(start):7        # with k chosen, record (remember to copy); otherwise pick one from start to n: choose, explore, un-choose8        pass9 10    go(1)11    return res12 13print(combine(4, 2))14print(len(combine(6, 3)))15print(combine(5, 3) == [list(c) for c in combinations(range(1, 6), 3)])
Output
Press Run or Ctrl+Enter

Pruning: do not go down dead ends

Pick some different numbers from [1, 2, 3, 4] that add up to exactly 5. Without pruning, all 16 subsets are walked and then checked for a sum of 5. But sort nums first, and there is a strong test: if the sum so far plus nums[j] is already over 5, the later numbers are only bigger, and the whole loop can break.

0

Picking numbers from [1, 2, 3, 4] to make 5: sorted, so once over 5 it breaks and the later siblings are never tried; the crossed ones are tried and cut at once

Count the nodes:

main.py
1calls = 02 3def sum_all(nums, target):           # no pruning: walk all 16 subsets4    res, path = [], []5    def go(start, total):6        global calls7        calls += 18        if total == target:9            res.append(path[:])10        for j in range(start, len(nums)):11            path.append(nums[j])12            go(j + 1, total + nums[j])13            path.pop()14    go(0, 0)15    return res16 17def sum_pruned(nums, target):        # nums sorted, smallest first18    res, path = [], []19    def go(start, total):20        global calls21        calls += 122        if total == target:23            res.append(path[:])24            return                   # adding more only makes it bigger25        for j in range(start, len(nums)):26            if total + nums[j] > target:27                break                # prune: the later numbers are bigger, even worse28            path.append(nums[j])29            go(j + 1, total + nums[j])30            path.pop()31    go(0, 0)32    return res33 34for nums, target in [([1, 2, 3, 4], 5), (list(range(1, 15)), 14)]:35    calls = 036    a = sum_all(nums, target)37    plain = calls38    calls = 039    b = sum_pruned(nums, target)40    print(f"{len(a)} answers, same? {a == b}; nodes: {plain} unpruned, {calls} pruned")41print(sum_pruned([1, 2, 3, 4], 5))
Output
2 answers, same? True; nodes: 16 unpruned, 9 pruned
22 answers, same? True; nodes: 16384 unpruned, 110 pruned
[[1, 4], [2, 3]]

Picking from 1 to 14 to make 14: 22 answers either way, but without pruning the search walks 16384 nodes, and with it only 110. Pruning never changes the answers; it just does not go down paths that cannot work. Common cuts: break once over the target after sorting; stop when too few numbers are left to make k; in N-queens, do not place on an attacked square (lesson 6).

In interviews: for a backtracking problem, draw the first two or three levels of the tree and say "what each step can choose, when to record, what can be cut" before writing code. The two follow-up questions you will hear most: why record path[:]; and how to skip duplicates when the numbers repeat ([1, 1, 2]): sort, then skip a number equal to the one before it at the same level (if j > start and nums[j] == nums[j - 1]: continue).

Fill inTap one to fill a blank; tap a blank to take it back

nums is sorted from small to large. This comparison decides when to prune: fill in the blank so the program finds the sums of 5, [[1, 4], [2, 3]].

1def sum_pruned(nums, target):2    res, path = [], []3 4    def go(start, total):5        if total == target:6            res.append(path[:])7            return8        for j in range(start, len(nums)):9            if total + nums[j]  target:10                break11            path.append(nums[j])12            go(j + 1, total + nums[j])13            path.pop()14 15    go(0, 0)16    return res17 18print(sum_pruned([1, 2, 3, 4], 5))
Exercise 2

Generating brackets

Complete gen(n): return every valid string of n pairs of brackets, in lexicographic order (( before )). Prune: add ( only while fewer than n have been used; add ) only while there are fewer closing than opening brackets.

It should print
['()']
['((()))', '(()())', '(())()', '()(())', '()()()']
42
exercise2.py
1def gen(n):2    res, path = [], []3 4    def go(opened, closed):5        # at length 2n, record "".join(path)6        # try "(" first, then ")": each time append, explore, pop7        pass8 9    go(0, 0)10    return res11 12print(gen(1))13print(gen(3))14print(len(gen(5)))
Output
Press Run or Ctrl+Enter

How you write it at work

When all you need is "every permutation", "every combination" or "each place chosen from a few options", the standard library's itertools has them, produced in lexicographic order, with no backtracking to write:

main.py
1from itertools import permutations, combinations, product2import math3 4print(list(permutations([1, 2, 3])))5print(list(combinations([1, 2, 3, 4], 2)))6print(list(product("ab", repeat=2)))7print(math.perm(5), math.comb(10, 3), len(list(product(range(10), repeat=4))))8 9count = 010checked = 011for r in range(15):12    for c in combinations(range(1, 15), r):13        checked += 114        if sum(c) == 14:15            count += 116print(count, "answers,", checked, "combinations checked")
Output
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
120 120 10000
22 answers, 16384 combinations checked
  • permutations(xs) gives every ordering, permutations(xs, k) orderings of k; combinations(xs, k) gives choices of k without order; product(xs, repeat=k) chooses every place from xs (the combination lock). They produce tuples, made one at a time, without taking a big block of memory first.
  • If you need only how many, not the answers themselves, use the formulas: math.perm, math.comb, no listing.
  • itertools can only list everything; it never prunes: for the make-14 problem it checks 16384 combinations where the hand-written search walks 110 nodes. When there are constraints and dead ends can be spotted early (combination sum, N-queens, sudoku), write the backtracking yourself.
Guess the outputA wrong guess is fine

How many does combinations give, and how many permutations?

1from itertools import combinations, permutations2 3print(len(list(combinations(range(5), 2))), len(list(permutations(range(5), 2))))

Summary

Take-away

Backtracking: choose, explore, un-choose

  • A path from the root to a leaf is one answer; the code is the tree's preorder walk
  • path.append, the call, path.pop() match up; after the undo, path is as before
  • Record with res.append(path[:]): without the copy, every result is the same empty list
  • n! permutations, 2ⁿ subsets, C(n, k) combinations: only for small n
  • Pruning keeps the answers and skips dead ends; with no constraints, use itertools
1def go(start):2    res.append(path[:])3    for j in range(start, len(nums)):4        path.append(nums[j])5        go(j + 1)6        path.pop()