Recursion and Recursive Thinking
📖 Introduction
🎯 What Is Recursion?
The Two Essential Components
def factorial(n: int) -> int:
"""
Calculate n! = n × (n-1) × (n-2) × ... × 1
Base case: 0! = 1 or 1! = 1
Recursive case: n! = n × (n-1)!
"""
# Base case
if n <= 1:
return 1
# Recursive case
return n * factorial(n - 1)
# Trace factorial(5):
# factorial(5) = 5 * factorial(4)
# = 5 * (4 * factorial(3))
# = 5 * (4 * (3 * factorial(2)))
# = 5 * (4 * (3 * (2 * factorial(1))))
# = 5 * (4 * (3 * (2 * 1)))
# = 5 * (4 * (3 * 2))
# = 5 * (4 * 6)
# = 5 * 24
# = 120📚 Understanding the Call Stack
Visualizing the Stack
Stack Frame Contents
Python's Recursion Limit
🎨 Designing Base Cases
Common Base Case Patterns
Base Case Errors
🔄 Recursive Patterns
Pattern 1: Linear Recursion
Pattern 2: Binary Recursion (Divide and Conquer)
Pattern 3: Tree Recursion
Pattern 4: Mutual Recursion
💾 Memoization
The Problem: Overlapping Subproblems
The Solution: Cache Results
When to Use Memoization
🔀 Tail Recursion
Regular vs Tail Recursion
Why Tail Recursion Matters
🔄 Converting Between Recursion and Iteration
Recursion to Iteration
Iteration to Recursion
When to Use Which
Use Recursion When
Use Iteration When
🧩 Classic Recursive Problems
Tower of Hanoi
Generate Permutations
Generate Subsets (Power Set)
Flood Fill
📝 Practice Exercises
Exercise 1: Sum of Digits
Exercise 2: Flatten Nested List
Exercise 3: String Combinations
🔑 Key Takeaways
🚀 What's Next?
📚 References
Last updated