3.7.7 · D3 · HinglishAlgorithm Paradigms

Worked examplesMemoization (top-down DP) — recursive + memo dict

2,795 words13 min read↑ Read in English

3.7.7 · D3 · Coding › Algorithm Paradigms › Memoization (top-down DP) — recursive + memo dict

Shuru karne se pehle, vocabulary ke baare mein ek waada. Ek state ek subproblem ka poora description hota hai — argument values ka woh set jo uska answer puri tarah decide karta hai. Ek memo (ya cache) ek dictionary hoti hai jiska key woh state hoti hai aur jiska value already-computed answer hota hai. Is page pe sab kuch yahi hai: state chuno, recurrence likho, state se cache karo, return karne se pehle store karo.


Scenario matrix

Har memoization problem inhi cells mein se kisi ek mein hoti hai. Neeche ke examples mein label diya gaya hai ki woh kaun si cell cover karte hain.

# Case class Kya naya / tricky hai Covered by
A 1-D state, 2-way branch textbook shape Ex 1
B Base case at zero (degenerate input) n = 0 ka matlab kya hai? Ex 1, Ex 2
C 1-D state, k-way branch do fixed calls nahi, balki ek loop pe recurse karo Ex 3
D 2-D state (tuple key) key mein dono variables hone chahiye Ex 4
E Negative / out-of-range state index karne se pehle guard lagao Ex 5
F Choice = max/min, not sum combine hamesha + nahi hota Ex 6
G Real-world word problem English → recurrence translate karo Ex 7
H Exam twist: stale-key bug wrong key silently kyun jhooth bolta hai Ex 8
I Limiting behaviour / complexity distinct states count karo Ex 9

Ex 1 — Fibonacci at a boundary (cells A, B)


Ex 2 — Climbing Stairs, kyun (cell B, Ex 1 se contrast)


Ex 3 — Coin-change count, ek k-way branch (cell C)


Ex 4 — Grid unique paths, ek tuple key (cell D)


Ex 5 — Ek aisi state jo negative ja sakti hai (cell E)


Ex 6 — Max-sum, jahan combine max hai + nahi (cell F)


Ex 7 — Word problem: decode-ways (cell G, real world)


Ex 8 — Exam twist: stale-key bug (cell H)


Ex 9 — Limiting behaviour: distinct states count karna (cell I)


Recall Har cell ka ek-line takeaway

Base value = DP ka aadha hissa ::: Ex 1 aur Ex 2 ke identical recurrences hain, alag answers hain. k-way branch = additions ka loop ::: Ex 3, Ex 7. 2-D state = tuple key ::: Ex 4; ek galat partial key silently jhooth bolta hai, Ex 8. Recurse karne se pehle base cases guard karo ::: Ex 5 negative indices se bachta hai. Counting ke liye combine sum hai, optimisation ke liye max/min ::: Ex 6. Time = distinct states × work per state ::: Ex 9.

Connections