Given an integer numRows, generate the first numRows rows of Pascal’s Triangle.
Each number is the sum of the two numbers directly above it.
-
Row starts and ends with
1. -
Inner numbers follow:
row[j] = prev_row[j - 1] + prev_row[j] -
Return as a list of lists.
One integer:
numRows
A 2D list representing Pascal’s Triangle.
Input:
numRows = 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Explanation:
Each row is created using the previous row.
Input:
numRows = 1
Output:
[
[1]
]
1 ≤ numRows ≤ 30
-
First and last elements of every row are
1. -
Each middle element is the sum of two numbers above it.
-
Build one row at a time.
-
Create an empty result list.
-
For each row index:
-
Start with all
1s. -
Update inner elements using previous row.
-
-
Append row to the triangle.
-
Time:
O(numRows²) -
Space:
O(numRows²)