[Solved] Given an integer numRows, return the first numRows of Pascal’s triangle. In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown.

Question

Given an integer numRows, return the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

PascalTriangleAnimated2

Example 1:

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

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

  • 1 <= numRows <= 30

Python Solution

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        l=[[1],[1,1],[1,2,1]]
        if numRows<=3:
            return l[:numRows]
        else:
            for i in range(3,numRows):
                a=[1]
                if i%2==0:
                    for j in range(i//2):
                        a.append(l[-1][j] + l[-1][j+1])
                    l.append(a+a[::-1][1:])
                else:
                    for j in range((i//2)+1):
                        a.append(l[-1][j] + l[-1][j+1])
                    l.append(a+a[::-1][2:])

            return l
Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *