Stop 10 · Data Structures & Algorithms in JavaTopics · 4/11

Recursion & Backtracking

Part of the Java Roadmap

In short

Trees, permutations, mazes and many DP problems are much easier to express when a method can call itself. Backtracking adds one more habit: try a choice, and undo it if it leads nowhere.

Recursion solves a problem by calling itself on smaller inputs until a base case. Backtracking builds solutions step by step and undoes choices that fail, as in permutations or N-Queens.

The jaadu walks back from a dead end in a tall green hedge maze, holding a piece of chalk next to arrows drawn on the path.

Think of it like this

Exploring a maze with chalk

Lost in a hedge maze at a fair, you mark each turning with chalk. At a dead end you walk back to the last mark and try the next path. You never wander the same dead end twice. Choose, explore, and un-choose is exactly what backtracking code does.

Watch it happen

Building permutations of 1, 2, 3

[ ]
[1]
[2]
[3]
[1,2]
[1,3]
[1,2,3]
[1,3,2]

1/5Start with an empty path and three unused numbers.

The big ideas

What you need to know

Base case first

Every recursive method needs a condition that stops it. Without one you get StackOverflowError.

Smaller each time

Each call must move towards the base case: n - 1, a shorter string, a smaller subtree.

Choose, explore, un-choose

Add a choice, recurse, then remove it. That undo step is what makes it backtracking.

The call stack

Every call takes stack memory. Recursion depth of n means O(n) space, even with no extra arrays.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.List;3 4public class Backtracking {5    static long factorial(int n) {6        if (n <= 1) return 1;            // base case7        return n * factorial(n - 1);     // smaller problem8    }9 10    static void permute(List<Integer> nums, List<Integer> path,11                        boolean[] used, List<List<Integer>> result) {12        if (path.size() == nums.size()) {13            result.add(new ArrayList<>(path));   // save a copy14            return;15        }16        for (int i = 0; i < nums.size(); i++) {17            if (used[i]) continue;18            used[i] = true;19            path.add(nums.get(i));                // choose20            permute(nums, path, used, result);    // explore21            path.remove(path.size() - 1);         // un-choose22            used[i] = false;23        }24    }25 26    public static void main(String[] args) {27        List<List<Integer>> result = new ArrayList<>();28        permute(List.of(1, 2, 3), new ArrayList<>(), new boolean[3], result);29        System.out.println(result);        // [[1, 2, 3], [1, 3, 2], [2, 1, 3], ...]30        System.out.println(factorial(5));  // 12031    }32}

1/4Classic recursion: a base case, then the same problem on n - 1.

Plain recursion with factorial, and backtracking that builds all six permutations of three numbers.

Save yourself the pain

Common mistakes

Oops

result.add(path) without copying.

Do this instead

path keeps changing, so every saved entry ends up empty. Save new ArrayList<>(path).

Oops

path.remove(Integer.valueOf(x)) vs path.remove(i) mix-ups.

Do this instead

On a List<Integer>, remove(int) removes by index and remove(Object) by value. Removing the last index is the safe undo.

Oops

Recursing a million levels deep on a linked list.

Do this instead

Java's default stack handles a few thousand frames comfortably. Use a loop for very deep inputs.

Your mission

Recursion ladder

~60 min

Quick check

What happens if a recursive method has no reachable base case?

Go deeper

  1. 1Write factorial, power and Fibonacci recursively, then trace the call stack.
  2. 2Generate all subsets and permutations of a small array.
  3. 3Learn what causes a StackOverflowError.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge