Part 16 / Topic 5 of 12
Recursion and backtracking
Recursion is a method calling itself on a smaller version of the same problem, with a base case that stops the chain and a recursive case that shrinks toward it. Backtracking is recursion with a pattern on top: choose one option, explore what follows from it, then un-choose (backtrack) before trying the next option — so every combination gets a fair, isolated try. Think of a courier planning stop orders: try stop A first, work out the rest of the route assuming A went first, then come back and try stop B first instead — nothing from trying A leaks into the attempt that starts with B.
static long fibonacciSlow(int n) {
if (n <= 1) return n; // base case
return fibonacciSlow(n - 1) + fibonacciSlow(n - 2); // recursive case: two smaller calls
}
static long fibonacciMemoized(int n, long[] memo) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n]; // already solved this one
memo[n] = fibonacciMemoized(n - 1, memo) + fibonacciMemoized(n - 2, memo);
return memo[n];
}
$ javac RecursionBacktrackingDemo.java
$ java RecursionBacktrackingDemo
-- factorial: base case + recursive case --
factorial(6) = 720
-- fibonacci: naive recursion vs memoized --
fibonacciSlow(35) = 9227465 (13 ms, varies)
fibonacciMemoized(35) = 9227465 (2 microseconds, varies)
same answer: true
-- backtracking: every pickup order for 3 stops --
[Kothrud, Baner, Aundh]
[Kothrud, Aundh, Baner]
[Baner, Kothrud, Aundh]
[Baner, Aundh, Kothrud]
[Aundh, Kothrud, Baner]
[Aundh, Baner, Kothrud]
total orders: 6 (3! = 6)
-- backtracking with pruning: parcel subsets under a 5 kg bag limit --
[groceries] = 4 kg
[shoes] = 1 kg
[shoes, groceries] = 5 kg
[laptop] = 3 kg
[laptop, shoes] = 4 kg
[books] = 2 kg
[books, shoes] = 3 kg
[books, laptop] = 5 kg
combinations that fit: 8
fibonacciSlow re-solves the same smaller fibonacci numbers over and over — its recursion tree doubles in size with every step up, which is why fibonacciSlow(35) is measured in milliseconds while the memoized version (section 10's dynamic-programming idea, used here one call early) is measured in microseconds for the identical answer. The last example adds pruning: backtrackSubsets returns immediately once currentWeight > limit, so it never wastes time exploring a branch that can only get heavier.
⚠️ Every recursive method needs a base case that is actually reachable. A recursive case that never shrinks toward the base case (or a base case with a typo in its condition) is a
StackOverflowErrorwaiting to happen, not an infinite loop you canCtrl+Cout of as easily.
Full program: examples/recursion-backtracking/RecursionBacktrackingDemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.