Recursion & Backtracking ā Complete Step-by-Step Guide
Module 8 ā Recursion & Backtracking: Recursion, the call stack, divide and conquer, and backtracking Structured as Topic ā Plain-English Explanation ā Real Code ā Visual Diagram ā Complexity ā Common Pitfalls.
1. Recursion & The Call Stack
A function is recursive when it calls itself to solve a smaller version of the same problem. Every recursive function needs a base case ā a condition where it stops calling itself and returns directly ā otherwise it would call itself forever. Each call adds a new frame to the call stack; once the base case is hit, the calls "unwind," each frame returning its result to the one that called it.
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
2. Divide and Conquer
Divide and conquer is a recursive strategy with three steps:
- Divide: Split the problem into smaller subproblems of the same type.
- Conquer: Solve each subproblem recursively (until a base case is trivial to solve directly).
- Combine: Merge the subproblem results into the final answer.
Merge sort (Module 5) is the textbook example: divide the array in half, sort each half recursively, then merge the sorted halves.
3. Backtracking
Backtracking is a refinement of recursion for exploring all possible choices to a problem: it builds a solution incrementally, and the moment it discovers the current partial solution can't possibly lead to a valid answer, it backtracks ā undoes the last choice and tries a different one ā rather than exploring every possibility to the end. This pruning is what makes backtracking far faster than brute force for problems like N-Queens, Sudoku, and generating permutations.
void permute(vector<int>& nums, vector<int>& current, vector<bool>& used) {
if (current.size() == nums.size()) {
/* record solution */
return;
}
for (int i = 0; i < nums.size(); i++) {
if (used[i]) continue;
used[i] = true;
current.push_back(nums[i]);
permute(nums, current, used); // choose
current.pop_back(); // un-choose (backtrack)
used[i] = false;
}
}