The problem, in one line. Given a count of rows, build that many rows of Pascal’s triangle, where each inner number is the sum of the two numbers above it. LeetCode 118.
The tell. The statement hands you the rule: a cell is built from cells in the row before it. When the answer is a grid and each cell leans on earlier cells, you are filling a table, which is the whole idea of 2-D dynamic programming.
The wrong first idea
Write the rule as a recursive function and ask for each cell directly: cell(r, c) = cell(r-1, c-1) + cell(r-1, c), with 1 on the edges.
def cell(r, c):
if c == 0 or c == r:
return 1
return cell(r - 1, c - 1) + cell(r - 1, c)
It is correct, and it forgets everything. The middle of row 30 is 155,117,520, and because every call ends in a 1, the recursion makes that many calls to reach it. Each cell is worked out again by every cell below it.
The invariant
Build one row at a time and keep the rows you already built. When you start row i, row i - 1 is finished and sitting in the list, so each inner cell is two lookups and one add.
flowchart TD A["[1]"] --> B["[1, 1]"] B --> C["[1, 2, 1]<br/>2 = 1 + 1"] C --> D["[1, 3, 3, 1]<br/>3 = 1 + 2, 3 = 2 + 1"]
The sentence that stays true every step: the previous row is complete and never changes again. That is why each cell is computed exactly once.
The solution
def generate(n):
rows = []
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = rows[-1][j - 1] + rows[-1][j] # each cell is the two above it
rows.append(row)
return rows
print(generate(5))
print(generate(1))
print(generate(2))
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
[[1]]
[[1], [1, 1]]
func generate(n int) [][]int {
rows := [][]int{}
for i := 0; i < n; i++ {
row := make([]int, i+1)
for j := range row {
row[j] = 1
}
for j := 1; j < i; j++ {
row[j] = rows[i-1][j-1] + rows[i-1][j] // each cell is the two above it
}
rows = append(rows, row)
}
return rows
}
Same three calls print [[1] [1 1] [1 2 1] [1 3 3 1] [1 4 6 4 1]], [[1]], [[1] [1 1]].
Complexity
- Time O(n squared): row
ihasi + 1cells and each costs one add, so the total is about n squared over two. - Space O(n squared): the answer itself stores every cell, so nothing smaller is possible.
Traps
- Filling the inner cells from a row that is still all zeros. Start each row as all ones, then overwrite only positions 1 to
i - 1, or the edges come out as 0. - Looping
jup toiinstead ofi - 1. Forn = 2that overwrites the last 1 with a sum that reads past the row above. - Returning one row’s worth of rows. For
n = 1the answer is[[1]], a list holding a list, not[1].
Next in the ladder
Unique Paths uses the same “this cell is the cell above plus the cell to the left” move, but the grid is a map you walk across instead of a triangle you print.