Learn / Recursion and backtracking

Recursion trees

Many problems build an answer one choice at a time: the next bracket, the next letter, the next part of an IP address. Drawing those choices as a tree makes the code obvious. Each node is a partial answer, each branch is one choice, and each leaf is a finished answer. The recursion walks the tree, and a rule prunes branches that can never work.

How to recognise it

  • The question says "generate all", "list every", or "all possible" strings or combinations.
  • The answer is built step by step, and each step has a small number of choices.
  • Some partial answers can be ruled out early (too many closing brackets, a part bigger than 255).

The idea in one picture

Write the empty answer at the top of a page. Below it, draw one branch for every choice you could make first. Below each of those, a branch for every second choice, and so on. The finished answers are the leaves. The recursion is just a walk over this drawing, left to right.

ProblemOne level of the treePruning rule
Generate Parenthesesadd ( or )( while open is below n, ) while close is below open
Letter Combinationspick a letter of the next digitnone needed
IP addressestake the next 1, 2 or 3 digits as a partno leading zero, at most 255, exactly 4 parts
Sentences from word listspick a word from the next listnone needed
Remove Invalid Parenthesesremove one more bracket (breadth-first)stop at the first level with a valid string

Template: choose, recurse, undo

function build(state):
    if state is a complete answer: record it; return
    for each choice allowed from state:
        apply choice
        build(state)
        undo choice

Counting the work

The number of leaves is the product of the choices per level, so these trees grow fast. That is expected: when the question asks for every answer, the output itself is that big. Pruning cuts away whole subtrees that cannot lead to a valid answer.

Common mistakes

  • Forgetting to undo, so one branch's choice leaks into the next.
  • Recording an answer by reference (a shared list) instead of a copy.
  • Pruning too late: checking validity only at the leaf costs far more than stopping as soon as a rule breaks.

Problems

0 of 5 solved

Check yourself

In Generate Parentheses with n pairs, when may you add a closing bracket?

Why do backtracking solutions undo a choice after the recursive call returns?

How many leaves does the tree for Letter Combinations of "234" have?