Instagram
youtube
Facebook
Twitter

Pascal's Triangle Leetcode Solution

In this tutorial, we are going to solve a leetcode  Pascal's Triangle in python.

Task:

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:

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

Solution:

from math import factorial
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        lst, m = [], []
        for i in range(numRows):
            for j in range(i+1):
                am = factorial(i) // (factorial(i-j) * factorial(j))
                m.append(am)
            lst.append(m)
            m = []
        return lst

Steps:

step1: First we will declare two empty lists that will return our answer. 

step2: then we add 2 loops, first will loop over the numRows and another loop will run till (i+1) times. And inside the inner loop we apply some mathematics for calculating the value of variable am and appending it to the list m.

step3: Outside the inner loop but still inside the outer loop we append the m to our lst which is our required returned list for the solution.

step4: after appending on the lst, we again make the m empty in order to add new row values. And then we return the lst.