Pascal's Triangle
Difficulty: Easy · Pattern: 2-D Dynamic Programming · LeetCode #118
Return the first numRows rows of Pascal's triangle, where each number is the sum of the two numbers directly above it.
Example
text
numRows = 5 → [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]Hints
- Row r has r+1 entries. The ends are 1, and
row[j] = prev[j−1] + prev[j].
Approach
Build each row from the previous one. This is the simplest 2-D DP, and entry j of row r is the binomial coefficient C(r, j). That's why Pascal's triangle also counts grid paths (Unique Paths).
Complexity
Time: O(n²). Space: O(n²) for the output.
Python solution
def generate(numRows):
rows = [[1]]
for _ in range(numRows - 1):
prev = rows[-1]
rows.append([1] + [prev[j - 1] + prev[j] for j in range(1, len(prev))] + [1])
return rows[:numRows]JavaScript solution
function generate(numRows) {
const rows = [[1]];
for (let r = 1; r < numRows; r++) {
const prev = rows[r - 1], row = [1];
for (let j = 1; j < r; j++) row.push(prev[j - 1] + prev[j]);
row.push(1);
rows.push(row);
}
return rows;
}