Recursion & Backtracking · Pattern 1 of 9

Basic recursion: base cases, structures and paths

Write the answer in terms of a smaller version of the same problem, and stop at a base case. The same habit walks trees and nested lists, and with an undo step it becomes the backtracking template.

4 variations · 7 problems · 6 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The answer for n is easy once you know the answer for n − 1
  • The input is itself recursive: a tree, or a list that holds lists
  • You need every root-to-leaf path, or every sequence of choices

The template

Basic Recursion
long factorial(int n) {
    if (n <= 1) return 1;                 // base case: stops the recursion
    return n * factorial(n - 1);          // a smaller version of the same problem
}

// Fibonacci with a memo: each value is computed once, O(n) instead of O(2^n)
Map<Integer, Integer> memo = new HashMap<>();
int fib(int n) {
    if (n <= 1) return n;
    if (memo.containsKey(n)) return memo.get(n);
    int res = fib(n - 1) + fib(n - 2);
    memo.put(n, res);
    return res;
}

// the backtracking skeleton: every sequence of len distinct choices
List<List<Integer>> sequences(int[] choices, int len) {
    List<List<Integer>> out = new ArrayList<>();
    backtrack(choices, len, new boolean[choices.length], new ArrayList<>(), out);
    return out;
}
void backtrack(int[] choices, int len, boolean[] used, List<Integer> path, List<List<Integer>> out) {
    if (path.size() == len) { out.add(new ArrayList<>(path)); return; }   // record a copy
    for (int i = 0; i < choices.length; i++) {
        if (used[i]) continue;                         // skip invalid choices
        used[i] = true; path.add(choices[i]);          // choose
        backtrack(choices, len, used, path, out);      // explore
        path.remove(path.size() - 1); used[i] = false; // un-choose
    }
}

The variations

  1. 1Answer from smaller answers

    Write f(n) using f(n − 1) and f(n − 2), then the base cases. Draw the call tree once: you will see why the plain version is exponential and why a memo fixes it.

  2. 2Recurse on a recursive structure

    A tree node or a nested list contains smaller copies of itself. Handle one element, recurse on the children, and pass down whatever they need, such as the depth.

  3. 3Carry a path down, undo on the way up

    Add the current choice to a path, recurse, then remove it. At a leaf (or when the path is complete), save a copy. This is the template every later pattern reuses.

    Now you solve
  4. 4More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Plain recursive Fibonacci recomputes the same values again and again: O(2^n). Add a memo or loop from the bottom.
  • Building a path string and forgetting that Java and Python strings are immutable: pass path + "->" + val down and nothing needs undoing; with a shared list, you must undo.
  • For nested lists, pass the depth as a parameter instead of keeping one global counter that you forget to restore.
Next: N-Queens: place one queen per row →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.