Module 1: Top-Down DP (The Lazy Memory)
๐ Module 1: Top-Down Dynamic Programming
Course ID: DSA-401
Subject: The Lazy Memory
Top-Down is the most intuitive way to start with Dynamic Programming. You start with the big problem and break it into smaller pieces.
๐๏ธ Step 1: Recursion + Memoization
We already learned about this in Milestone 5 (Module 2).
- You write a recursive function.
- You check if the answer is in the โMemoryโ (Cache).
- If not, you calculate it and save it.
๐งฉ The Analogy: The Lazy Student
- Teacher: โWhat is 1+1+1+1?โ
- Student: (Calculates) โ4.โ
- Teacher: โWhat is 4 + 1?โ
- Student: (Doesnโt recalculate 1+1+1+1) โ5.โ
๐๏ธ Step 2: The Structure
def solve(n, memo):
# 1. Base case
if n <= 1: return n
# 2. Check memory
if n in memo: return memo[n]
# 3. Recursive step + Save
memo[n] = solve(n-1, memo) + solve(n-2, memo)
return memo[n]๐ฅ Module 1 Review
- Top-Down: Starting from and going down to .
- Memoization: The technical name for the cache.
- Recursion Stack: This method uses the system stack, so it can crash if is too large (Stack Overflow).
:::tip Slow Learner Note Top-Down is easier to write because it looks just like the math formula. If you can write the formula, you can write the code! :::