Data Structures & Algorithms · Module 6 · Lesson 21 min read

Backtracking

The idea

Build a solution step by step. At each step, try every valid choice; if it leads to a dead end, undo it (backtrack) and try the next one.

The template

Python
def backtrack(path, choices):
    if is_complete(path):
        results.append(path.copy())     # save a copy!
        return
    for choice in choices:
        if is_valid(choice, path):
            path.append(choice)         # choose
            backtrack(path, remaining)  # explore
            path.pop()                  # un-choose

Classic problems

ProblemChoices at each step
Subsetsinclude or skip each item: 2ⁿ results
Permutationsany unused item: n! results
Combinations / combination sumitems from index i onward
N-Queenswhich column for the queen in this row
Sudokuwhich digit for this empty cell
Word searchwhich neighbour cell to step into

Pruning: cut dead branches early

Stop exploring as soon as a path can't work, for example when the sum already exceeds the target. Good pruning makes exponential searches fast in practice.

Complexity

Usually exponential (O(2ⁿ), O(n!)), which is fine for small inputs and is exactly what these problems need.

⚠️ Common bug: appending path itself instead of path.copy(), so every saved result changes later.

Example

Python
def subsets(nums):
    result, path = [], []
    def go(i):
        if i == len(nums):
            result.append(path.copy())
            return
        path.append(nums[i]); go(i + 1); path.pop()   # include
        go(i + 1)                                     # skip
    go(0)
    return result

def permutations(nums):
    result, path, used = [], [], [False] * len(nums)
    def go():
        if len(path) == len(nums):
            result.append(path.copy())
            return
        for i, x in enumerate(nums):
            if not used[i]:
                used[i] = True; path.append(x)
                go()
                path.pop(); used[i] = False
    go()
    return result

def combination_sum(candidates, target):
    result = []
    def go(start, path, remaining):
        if remaining == 0:
            result.append(path.copy())
            return
        for i in range(start, len(candidates)):
            if candidates[i] <= remaining:            # pruning
                path.append(candidates[i])
                go(i, path, remaining - candidates[i])
                path.pop()
    go(0, [], target)
    return result

print(subsets([1, 2, 3]))        # 8 subsets
print(permutations([1, 2, 3]))   # 6 orderings
print(combination_sum([2, 3, 6, 7], 7))   # [[2, 2, 3], [7]]