Dynamic Programming

Lesson 19 of 20

Watch a knapsack DP table fill row by row to a value of 7 — and stair-count ways stack up from two base cells.

The big picture

Why DP wins

Dynamic programming never solves the same subproblem twice — it fills a table once and reads the answer off the corner.

The core trick

Solve each subproblem once and store it — overlapping subproblems are the tell that DP applies.

Two styles

Memoization caches recursive calls top-down; tabulation fills a table bottom-up from base cases.

The knapsack table

dp[i][c] = best value from the first i items within capacity c — 24 cells for 3 items, cap 5.

Climbing stairs

ways[i] = ways[i-1] + ways[i-2] — Fibonacci in hiking boots: 1, 1, 2, 3, 5.

The win

Naive knapsack branches exponentially; the table flattens it to O(n × cap) — and beats greedy on coin {1,3,4}.