Data Structures & Algorithms / Module 9: Dynamic programming

Topic 9.2

Tabulation

Filling a table of answers from the smallest case up, with no recursion.

9 min · intermediate

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.

startgoal
  • moving now
  • being checked
  • finished / the result
Step 1 of 14

A 3 × 4 grid. From the top-left corner to the bottom-right, moving only right or down. How many routes are there?

Every cell only needs two cells that are already filled: above and to the left. Fill them in the right order, and the answer is waiting in the last corner.

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 cells

How to set up a table

  1. What does one cell mean? Say it in one sentence: "dp[r][c] = the number of routes to cell (r, c)".
  2. Where does its value come from? A formula using smaller cells: above + left.
  3. Base cases? Cells you can fill without the formula: the top and left edges.
  4. Fill order? An order where every cell you need is already filled: row by row.
  5. Where is the answer? The bottom-right corner.

Quiz

  1. What is the main difference between tabulation and memoization?

  2. Why is the grid filled row by row from the top?

  3. A 1,000 × 1,000 grid. Roughly what does it cost?

0 of 3 answered.