Skip to content

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

  1. Top-Down: Starting from NN and going down to 11.
  2. Memoization: The technical name for the cache.
  3. Recursion Stack: This method uses the system stack, so it can crash if NN 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! :::