def fib(n): if n < 2: return n return fib(n-1) + fib(n-2)
Memoization (top-down):
def fib(n, memo={}): if n < 2: return n if n in memo: return memo[n] # reuse — kills overlap memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n]
Yeh step kyun?if n in memo check ek exponential tree ko ek linear chain mein convert kar deta hai: har F(k) ek baar compute hota hai, phir cache se serve hota hai.
Tabulation (bottom-up):
def fib(n): if n < 2: return n dp = [0, 1] for i in range(2, n+1): dp.append(dp[i-1] + dp[i-2]) # smallest → largest return dp[n]
Yeh step kyun? Hum increasing i mein fill karte hain taaki dp[i−1],dp[i−2]pehle se computed hon — yahi ordering exactly "optimal substructure ko concrete banana" hai.
Items jinke weight wi, value vi hai, capacity W hai. Value maximize karo.
Recurrence derive karo. Item i ko remaining capacity c ke saath socho. Do choices hain:
Skip karo: best value hai K(i−1,c).
Lo (sirf tab agar wi≤c): vi gain karo + baaki ka best kam room ke saath: vi+K(i−1,c−wi).
Yeh optimal substructure kyun hai? Items 1..i ki best packing mein zaroori hai ki baaki bachi capacity ke liye 1..i−1 ki best packing ho — warna hum us better sub-packing ko swap karke poore ko improve kar sakte the. Overlap kyun hai? Kaafi alag item-prefixes same (i,c) pair tak pahunchte hain.
def knapsack(w, v, W): n = len(w) dp = [[0]*(W+1) for _ in range(n+1)] for i in range(1, n+1): for c in range(W+1): dp[i][c] = dp[i-1][c] # skip if w[i-1] <= c: dp[i][c] = max(dp[i][c], v[i-1] + dp[i-1][c-w[i-1]]) # take return dp[n][W]
Recall Feynman: ek 12-saal ke bacche ko explain karo
Socho ek homework jisme wahi chhota math problem 50 baar aata hai. Ek lazy-lekin-smart baccha use ek baar solve karta hai, jawab ek sticky note pe likhta hai, aur baaki 49 baar sirf copy karta hai. Yahi memoization hai. Tabulation mein pehle saare chhote problems karo, order mein, bade wale se pehle — jaise Lego ko neeche ke blocks se upar ki taraf banao. Trick tabhi kaam karti hai kyunki (1) wohi chhote problems baar baar repeat hote hain, aur (2) bada answer genuinely chhote answers se bana hota hai.