Dynamic Programming — Foundations

bottom-up tabulation

Instead of starting from the big question and recursing down to the small ones, you start from the smallest answers you already know and build upward, filling a table row by row until the big answer is the last cell you write. It is like assembling a tower of blocks: you cannot place a higher block until the ones it rests on are in place, so you lay the foundation first and work up. There is no recursion at all — just loops that fill an array in a carefully chosen order.

The recipe is: allocate a table indexed by the state, write the base-case entries directly, then loop over the states in an order that guarantees every entry is computed only after all the entries it depends on, applying the transition to fill each cell from earlier cells. For Fibonacci: make an array f, set f[0]=0 and f[1]=1, then for i from 2 to n set f[i]=f[i-1]+f[i-2]; the answer is f[n]. The loop order from small i to large i is exactly what makes f[i-1] and f[i-2] already available when you need them. The running time is again (number of states) times (work per transition), but now with no function-call overhead and no stack.

Tabulation's payoffs are speed and predictable memory. Because the fill order is explicit, you can often shrink space dramatically: Fibonacci only ever looks back two cells, so two scalar variables suffice instead of the whole array, giving O(1) space. The price is that you must work out a valid evaluation order yourself, and a naive tabulation computes every state in the table even ones the answer never actually needs — whereas a top-down memoization touches only reachable states. So tabulation trades a little flexibility for raw efficiency and stack safety.

Space-optimized Fibonacci by tabulation: a=0, b=1; repeat n times: (a,b)=(b,a+b); answer is a. Two variables, O(n) time, O(1) space — possible only because the explicit fill order tells you exactly how far back you ever need to look.

Knowing the fill order lets you keep only the few cells still needed, shrinking memory.

Getting the loop order wrong is the classic tabulation bug: if you read a cell before it is filled, you use a stale or zero value and the answer is silently wrong. Always confirm every transition reads only earlier-filled cells.

Also called
tabulationiterative DP表格法迭代式動態規劃