SDE & MLE Prep

118. Pascal's Triangle

Problem

Return the first numRows rows of Pascal's triangle, where every number is the sum of the two numbers diagonally above it and each row starts and ends with 1.

Example: numRows = 5 → [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Each row starts and ends with 1; inner values are the sum of the two values above.

Complexity: O(n²).

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        rows = [[1]]
        for _ in range(numRows - 1):
            prev = rows[-1]
            rows.append([1] + [prev[i] + prev[i + 1] for i in range(len(prev) - 1)] + [1])
        return rows