Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Pascal's triangle is built from a local rule: boundary entries are one, and each interior entry is the sum of the two entries above it. Since the input never requests more than 30 rows, the reference solutions construct that fixed table once and reuse it for every call.
Approach
- Outside the solution method, allocate 30 rows of lengths one through 30, initially filled with ones. This already establishes both boundaries and the first two rows.
- Starting at the third row, replace every interior entry with
previous[j - 1] + previous[j]. Earlier rows are complete before they are used. - For a request of
numRows, return a slice containing the firstnumRowsprecomputed rows. This copies the outer list of references, not the individual rows; the reference implementation does not rebuild the triangle for each request.
pas = []
row_size = 1
for i in range(30):
pas.append([1] * row_size)
row_size += 1
for i in range(2, 30):
for j in range(len(pas[i])):
if j == 0 or j == len(pas[i]) - 1: continue
pas[i][j] = pas[i - 1][j - 1] + pas[i - 1][j]
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
return pas[:numRows]Complexity analysis
The module precomputes the fixed 30-row table once in O(30²) time and O(30²) storage. A call with r = numRows shallow-copies r row references in O(r) time and O(r) returned outer-list space; the row data is shared with the precomputed table.
