Dynamic Programming

Lesson 19 of 20

Fill a knapsack table cell by cell, watch fib’s memo erase repeat work, and learn why the 1-D loop must run backwards.

The big picture

The big picture

Stop re-solving the same subproblems: cache each answer once, and exponential call trees collapse into neat tables.

One idea, two styles

Memoization caches on the way down (top-down); tabulation fills a table on the way up (bottom-up). Same answers, opposite directions.

Overlapping subproblems

Naive fib(6) makes 25 calls and recomputes fib(3) twice; the memoized version answers every subproblem exactly once.

The knapsack question

Every cell asks one thing: is item i worth more skipped, or taken on top of the best load that fit before it?

The recurrence

dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt[i]] + val[i]) — skip versus take, written in a single line.

The price tag

n items × W capacities = O(n × W) cells — pseudo-polynomial, and vastly cheaper than enumerating 2^n subsets.

The 1-D squeeze

One rolling row can replace the whole table — provided the capacity loop runs backwards.