← Learning Hub
Intermediate

Recursion

A recursive method calls itself on a smaller problem. It needs a base case that stops it, or you get a StackOverflowError.

Recursion breaks a problem into smaller copies of itself. It's the natural way to handle trees, subsets and backtracking, and the starting point for dynamic programming.

Example
You can edit this code.

Generating all subsets (backtracking)

Example
You can edit this code.

Why naive Fibonacci is slow

Example
You can edit this code.

Each call makes two more, so the work explodes (about 2n). The Dynamic Programming lesson fixes this.

Key points
  • Every recursion needs a base case.
  • Backtracking: choose, explore, undo.
  • Naive recursion can repeat work - DP fixes it.

📝 Test yourself

1. What stops a recursive method?
2. How many subsets do 3 items have?
3. Fill in the error thrown by endless recursion:
Error