Backtracking
Backtracking is a depth-first search that builds a candidate incrementally, abandons it as soon as it cannot lead to a valid solution, and undoes the last choice before trying the next.
Detailed Explanation
Brute force enumerates every complete assignment. Backtracking enumerates partial assignments and prunes. N-queens, Sudoku, subset-sum, permutations, and path-finding with constraints are the usual examples. You place a choice, recurse, then remove the choice — that removal is the "backtrack".
The skeleton is: if the candidate is complete, record it; otherwise, for each legal next choice, apply it, recurse, undo it. The undo must restore the exact previous state. Mutating a board and appending to a path are fine if you pop and reset. Copying the whole board on every call also works and is slower.
Pruning is the performance. Do not try a queen that shares a column or diagonal. Do not continue a subset that already exceeds the target. The earlier you reject, the smaller the tree. Ordering choices (try most constrained first) can change the constant a lot and not the worst-case exponential.
Worst case remains exponential. Backtracking is for n that is small or heavily constrained. For optimisation with overlapping subproblems, DP may be better. For unweighted shortest paths, BFS is better.
In Python, recursion is the readable form. The depth is the length of the candidate. For permutations of 20 items you will not finish; for n=9 Sudoku the constraints save you. Pass a shared mutable structure plus an index, not a sliced copy on every call.
yield from turns the search into a generator of solutions so the caller can stop after the first.
Code Examples
def permutations(items: list[str]) -> list[list[str]]:
used = [False] * len(items)
path: list[str] = []
out: list[list[str]] = []
def walk() -> None:
if len(path) == len(items):
out.append(path.copy())
return
for i, item in enumerate(items):
if used[i]:
continue
used[i] = True
path.append(item)
walk()
path.pop()
used[i] = False
walk()
return out
print(permutations(["A", "B"])) # [['A', 'B'], ['B', 'A']]def subsets_that_sum(nums: list[int], target: int) -> list[list[int]]:
nums = sorted(nums)
path: list[int] = []
out: list[list[int]] = []
def walk(start: int, remaining: int) -> None:
if remaining == 0:
out.append(path.copy())
return
for i in range(start, len(nums)):
if nums[i] > remaining:
break
path.append(nums[i])
walk(i + 1, remaining - nums[i])
path.pop()
walk(0, target)
return out
print(subsets_that_sum([2, 3, 5], 5)) # [[2, 3], [5]]Common Gotchas
Forgetting to undo
the next branch sees a dirty board. Pair every `append` with a `pop`.
Appending `path` instead of `path.copy()`
every recorded solution is the same list object, emptied at the end.
No prune means brute force
if the tree is the full n!, n=12 is already huge.
Recursion limit equals candidate length
that is usually fine; the time cost appears first.