Generate Pascal's Triangle up to numRows.
Problem Statement
Examples
Input: numRows = 5
Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
Explanation: Combining the input according to Pascal's Triangle I logic yields [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]].
Input: numRows = 1
Output: [[1]]
Explanation: Combining the input according to Pascal's Triangle I logic yields [[1]].
Complexity
Time Complexity: O(N²)
Space Complexity: O(N²)
Hints
Editorial & Approach
Problem Overview & Intuition
Every row starts and ends with 1. Each intermediate cell at row i and column j is the sum of result[i - 1][j - 1] and result[i - 1][j]. Building iteratively row by row takes O(numRows²).
Step-by-Step Approach
- Initialize
result = []. - Loop
ifrom0tonumRows - 1. - Construct a new row of size
i + 1filled with1. - For
jfrom1toi - 1: setrow[j] = result[i - 1][j - 1] + result[i - 1][j]. - Append
rowtoresult. - Return
result.
Optimal Implementation (JavaScript)
function generatePascalsTriangle(numRows) {
const result = [];
for (let i = 0; i < numRows; i++) {
const row = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) {
row[j] = result[i - 1][j - 1] + result[i - 1][j];
}
result.push(row);
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- numRows = 1: returns [[1]].
- numRows = 2: returns [[1], [1, 1]].