Data Structures & Algorithms / Module 9: Dynamic programming
Topic 9.2
Tabulation
Filling a table of answers from the smallest case up, with no recursion.
Watch: each cell is filled from two cells already done: the one above and the one to its left. The final answer is in the last corner.
- moving now
- being checked
- finished / the result
Memo from the top, table from the bottom
Memoization starts from the big question and works down to small ones as needed. Tabulation goes the other way: answer all the small questions first, then build up. The result is the same. The difference: with a table you choose the fill order yourself, so you must know up front which cells depend on which.
Routes across a grid
How many routes run from the top-left corner to the bottom-right if you may only move right or down? Every cell can only be reached from above or from the left. So routes to a cell = routes to the cell above + routes to the cell on its left. The top and left edges have one route each: straight. Fill row by row, and every cell you need is already done.
Code, for programmersFilling the table row by row
function gridRoutes(rows, cols) {
const dp = Array.from({ length: rows }, () => Array(cols).fill(1)); // edges: 1 route
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
dp[r][c] = dp[r - 1][c] + dp[r][c - 1]; // from above + from the left
}
}
return dp[rows - 1][cols - 1];
}
gridRoutes(3, 4); // 10
gridRoutes(10, 10); // 48620, from 100 cellsHow to set up a table
- What does one cell mean? Say it in one sentence: "dp[r][c] = the number of routes to cell (r, c)".
- Where does its value come from? A formula using smaller cells: above + left.
- Base cases? Cells you can fill without the formula: the top and left edges.
- Fill order? An order where every cell you need is already filled: row by row.
- Where is the answer? The bottom-right corner.
Quiz
What is the main difference between tabulation and memoization?
Why is the grid filled row by row from the top?
A 1,000 × 1,000 grid. Roughly what does it cost?
0 of 3 answered.