118. Pascal's Triangle

https://leetcode.com/problems/pascals-triangle/ Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

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

Solution

class Solution(object):
    def generate(self, numRows):

        if numRows == 0:
            return []
        
        Ans = []
        Ans.append([1])
        for i in range(1,numRows):
            Ans.append([])
            a = 1
            Ans[i].append(1)
            while a < i:
                Ans[i].append( Ans[i-1][a-1]+Ans[i-1][a] )
                a += 1
            Ans[i].append(1)
                
        return Ans

Last updated