dynamic programming
The dynamic programming chapter builds a table for the knapsack problem
The value f[1][10] is computed from smaller states, row by row
That image is the method
You are not searching for an answer
You are filling in answers to smaller questions until the real question is already solved
The two conditions
- overlapping subproblems
- optimal substructure
If the same state comes back, memoise If the best answer to the big problem is built from best answers to small ones, a recurrence exists
Without both, this is just caching with a fancy name Java would create a Factory for the cache and still compute the wrong thing
Memoisation
#include <unordered_map>
long long fib(long long n, std::unordered_map<long long, long long> &memo) {
if (n < 2) return n;
if (memo.contains(n)) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
fib(10) returns 55
Without the cache the same calls repeat exponentially
With the cache each value is computed once
That is the simplest demonstration, not the most useful one
Worked recurrence
Knapsack asks: given items with weight and profit, which subset fits a capacity and maximises profit
Define f[i][y] as the best profit using items from i onward with capacity y
The choice for item i:
- skip it, take
f[i+1][y] - take it if it fits, profit plus
f[i+1][y-weight[i]]
Pick the larger Rows are computed from the last item backward The final answer sits at the first row and full capacity
Top down versus bottom up
Top down starts at the question and recurses, caching on the way Bottom up starts at the smallest states and fills the table
Top down is easier to write Bottom up is easier to reason about memory Both compute the same states
The table is a design choice
The shape of f decides everything
Too few dimensions and you lose information
Too many and the table explodes
Ask: what do I need to know to decide the next step That becomes the state
Memory
A memo map or a table is memory spent to avoid time For large capacities the table can be enormous Sometimes you only need the final value and can keep two rows
Mistakes
- caching a function whose result depends on hidden state
- defining a state that cannot support the transition
- assuming the recurrence is optimal without checking
- copying a knapsack table into a problem with different constraints
Exercises
- Write the recurrence for fib with the state named explicitly
- For knapsack with three items, fill the table by hand for capacity five
- Change the problem to require using every item and see how the recurrence changes
- Explain when a bottom up table beats recursion
What to remember
Dynamic programming is table design Once the state is right, the code is short Getting the state wrong is very fast at producing wrong answers
Posted