Recursion and Backtracking Basics

Lesson 8 of 20

Four factorial frames stack up and pop off in reverse, while fib(4) branches into a tree of repeat calls.

The big picture

Meet recursion

A function that calls itself sounds like a trap — with a base case it becomes the cleanest tool in the box, powering everything from file trees to maze solvers.

A function calls itself

factorial(4) waits on factorial(3), which waits on factorial(2) — each call shrinks n by 1.

Base case first

The exit ramp: factorial stops at n == 1. Without it the calls never end.

The call stack

Every call pushes a frame; every return pops one. Python allows ~1000 frames before RecursionError.

Backtracking

Recurse on a choice, then undo it — picked.append(x) explores, picked.pop() backtracks.

The hidden bill

Naive fib(4) calls itself 9 times because fib(2) is computed twice — overlapping subproblems.