Dynamic Programming

Lesson 19 of 20

Fill a 4×6 knapsack table row by row and tabulate Fibonacci — every subproblem solved once, then reused forever.

The big picture

Recursion, with a memory

Dynamic programming is recursion that refuses to repeat itself: solve each subproblem once, write the answer down, and look it up forever after.

The bill naive recursion pays

Naive fib(6) recomputes fib(2) five times and fib(3) three times. A cache turns that exponential tree into a straight line.

Two ingredients

Overlapping subproblems + optimal substructure. When both hold — fib, knapsack, LCS — DP applies; when they do not, it misfires.

Define the state

dp[i][w] = the best value using the first i items within capacity w. Write that one sentence down before any code.

Write the recurrence

Skip item i → dp[i-1][w]; take it → value[i] + dp[i-1][w - weight[i]]. The cell keeps the max of the two.

Fill in dependency order

Row by row, left to right — every cell reads only cells that already exist. The bottom-right corner is the answer.