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.
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
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
}
} def factorial(n):
if n <= 1:
return 1 # base case: stops the recursion
return n * factorial(n - 1) # a smaller version of the same problem
from functools import cache
@cache # memo: each value is computed once
def fib(n):
return n if n <= 1 else fib(n - 1) + fib(n - 2)
def sequences(choices, length): # the backtracking skeleton
out, path, used = [], [], [False] * len(choices)
def backtrack():
if len(path) == length:
out.append(path[:]) # record a copy
return
for i, c in enumerate(choices):
if used[i]:
continue # skip invalid choices
used[i] = True; path.append(c) # choose
backtrack() # explore
path.pop(); used[i] = False # un-choose
backtrack()
return out long 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)
unordered_map<int, int> memo;
int fib(int n) {
if (n <= 1) return n;
if (memo.count(n)) return memo[n];
return memo[n] = fib(n - 1) + fib(n - 2);
}
// the backtracking skeleton: every sequence of len distinct choices
void backtrack(vector<int>& choices, int len, vector<bool>& used, vector<int>& path, vector<vector<int>>& out) {
if ((int)path.size() == len) { out.push_back(path); return; } // record a copy
for (int i = 0; i < (int)choices.size(); i++) {
if (used[i]) continue; // skip invalid choices
used[i] = true; path.push_back(choices[i]); // choose
backtrack(choices, len, used, path, out); // explore
path.pop_back(); used[i] = false; // un-choose
}
}
vector<vector<int>> sequences(vector<int>& choices, int len) {
vector<vector<int>> out;
vector<int> path;
vector<bool> used(choices.size(), false);
backtrack(choices, len, used, path, out);
return out;
} function factorial(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)
const memo = new Map();
function fib(n) {
if (n <= 1) return n;
if (!memo.has(n)) memo.set(n, fib(n - 1) + fib(n - 2));
return memo.get(n);
}
// the backtracking skeleton: every sequence of len distinct choices
function sequences(choices, len) {
const out = [], path = [], used = new Array(choices.length).fill(false);
function backtrack() {
if (path.length === len) { out.push([...path]); return; } // record a copy
for (let i = 0; i < choices.length; i++) {
if (used[i]) continue; // skip invalid choices
used[i] = true; path.push(choices[i]); // choose
backtrack(); // explore
path.pop(); used[i] = false; // un-choose
}
}
backtrack();
return out;
} The variations
-
1Answer from smaller answers
Write
f(n)usingf(n − 1)andf(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. -
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.
Now you solve -
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 -
4More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems- Tower of Hanoi Medium Stuck? ▶ video
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 + "->" + valdown 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.
Lesson done
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.