118 - Pascal’s Triangle

2020/06/17

leetcode

Problem

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Solution

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        ans = []

        for i in range(1, numRows+1):
            level = [1] * i

            if ans:
                for j in range(1, i-1):
                    level[j] = ans[-1][j-1] + ans[-1][j]

            ans.append(level)

        return ans