sagelearnai

Backtracking

Signal: "return all subsets / permutations / combinations / valid arrangements", puzzles (N-Queens, Sudoku), or a search over choices with constraints. Inputs are usually small (n ≤ ~15–20), because the output itself can be exponential.

Core idea: build a candidate one choice at a time. After exploring everything that follows a choice, undo it and try the next. Prune any branch that can no longer lead to a valid answer.

[ ] take 1skip 1 [1] [ ] [1,2] [1] [2] [ ] Decision tree for subsets of [1, 2]: each level decides one element;the leaves are the answers (2ⁿ of them).

The template

python
def backtrack(state, choices):
    if is_complete(state):
        results.append(state.copy())      # copy! state keeps changing
        return
    for c in choices(state):
        if not valid(state, c):           # prune early
            continue
        state.append(c)                   # choose
        backtrack(state, ...)             # explore
        state.pop()                       # un-choose

Three things to get right:

  1. What's the state, and when is it complete?
  2. What choices are available, and how do you avoid duplicates? Use a start index for combinations; sort and skip equal neighbors for duplicate inputs; use a used[] array for permutations.
  3. Pruning: stop when the remaining sum is negative, when a queen is attacked, and so on.
Problem typeBranchingCount
Subsetsinclude/exclude each element2ⁿ
Permutationsany unused element nextn!
Combinations of size kelements after startC(n, k)

Problems

  1. Subsets (Medium): Each element is in or out; or extend from a start index
  2. Subsets II (Medium): Sort; at each depth skip a value equal to the previous sibling
  3. Combination Sum (Medium): Reuse allowed → recurse with same start; prune on overshoot
  4. Combination Sum II (Medium): Sort; each number used once; skip equal siblings; prune when > remaining
  5. Combinations (Medium): Choose increasing numbers; prune when not enough numbers remain
  6. Permutations (Medium): Choose any unused element next
  7. Permutations II (Medium): Sort + used[]; skip nums[i] if equal to nums[i-1] and nums[i-1] is not in use
  8. Letter Combinations of a Phone Number (Medium): One recursion level per digit; branch on its letters
  9. Generate Parentheses (Medium): Add '(' while opens < n; ')' while closes < opens
  10. Word Search (Medium): DFS from each cell, mark visited, unmark on return
  11. Palindrome Partitioning (Medium): Choose the next cut where s[start..end] is a palindrome; precompute isPal[i][j]
  12. N-Queens (Hard): One queen per row; sets for columns and both diagonals
  13. Sudoku Solver (Hard): Backtrack over empty cells with row/col/box bitmasks; pick the most constrained cell
  14. Combination Sum III (Medium): Choose k distinct digits 1–9 increasing; prune on sum
  15. Restore IP Addresses (Medium): Place 3 dots; each segment 1–3 digits, ≤ 255, no leading zero
  16. Letter Case Permutation (Medium): Each letter doubles the set (lower/upper); digits pass through
  17. Partition to K Equal Sum Subsets (Medium): Fill buckets one at a time with a bitmask of used numbers + memo on the mask
  18. Beautiful Arrangement (Medium): Fill positions from n down to 1 (most constrained first) with a used mask
  19. Word Break II (Hard): Memoized DFS: sentences(start) = word + each sentence of the rest