Pascal's Triangle
Pattern: Matrix traversal
Build the triangle row by row. Each row starts and ends with 1, and every inner value is the sum of the two values just above it in the previous row.
The problem
Given a whole number numRows, return the first numRows rows of Pascal's triangle. Row 0 is [1]. Each later row
is one longer, starts and ends with 1, and every other value is the sum of the two values above it. For example,
numRows = 5 gives [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]].
The function name generate matches LeetCode. Use the link above for the exact statement and limits.
Think first
- How long is row
r, and which of its cells are always 1? - Which two cells of row
r - 1sit just above cellcof rowr? - Do you need anything older than the previous row?
Hints
Brute force, and why it fails
You could compute each value as C(r, c) with factorials, but factorials overflow quickly and take O(r) work per cell.
Building from the row above costs O(1) per cell and never overflows for the sizes LeetCode uses.
The key insight
Each row depends only on the row before it. Fill the triangle top to bottom and every value you need is already there.
Dry run
| row | 0 |
|---|
numRows = 5. Row 0 is just [1]. Each new row starts as all 1s, and only its inner cells need filling.
The plan
rows = empty list
for r from 0 to numRows - 1:
row = list of r + 1 ones
for c from 1 to r - 1:
row[c] = rows[r - 1][c - 1] + rows[r - 1][c]
add row to rows
return rows
Complexity
- Time
O(numRows²)- Space
O(numRows²)
The triangle has about numRows² / 2 cells and each takes O(1) work. The output itself takes that much memory, and
nothing else is stored.
Edge cases
numRows = 1: just[[1]].numRows = 2:[[1], [1, 1]], with no inner cells at all.- Large rows: the middle values grow fast, but they fit in a 32-bit number for the first 30 rows.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> rows = new ArrayList<>();
for (int r = 0; r < numRows; r++) {
List<Integer> row = new ArrayList<>();
for (int c = 0; c <= r; c++) {
if (c == 0 || c == r) row.add(1); // the edges are always 1
else row.add(rows.get(r - 1).get(c - 1) + rows.get(r - 1).get(c)); // sum of the two above
}
rows.add(row);
}
return rows;
}
}C++
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> rows;
for (int r = 0; r < numRows; r++) {
vector<int> row(r + 1, 1); // the edges are always 1
for (int c = 1; c < r; c++) row[c] = rows[r - 1][c - 1] + rows[r - 1][c]; // sum of the two above
rows.push_back(row);
}
return rows;
}
};Python
class Solution:
def generate(self, numRows: int) -> list[list[int]]:
rows = []
for r in range(numRows):
row = [1] * (r + 1) # the edges are always 1
for c in range(1, r):
row[c] = rows[r - 1][c - 1] + rows[r - 1][c] # sum of the two above
rows.append(row)
return rowsCommon mistakes
- Filling cells 0 to
rfrom the row above, which reads past the ends of the previous row. - Reusing one list object for every row, so changing a row changes all of them.
- Starting the loop at row 1 and forgetting to add row 0.