Skip to main content

Command Palette

Search for a command to run...

118. Pascal's Triangle

Published
•1 min read•View as Markdown
B
Senior Software Engineer | Backend, Cloud, Data, Machine Learning

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]]

Solution:

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        """
        two pointer problem
        """
        # base case (first row) in result
        res = [[1]]
        # build the rest row
        for i in range(numRows - 1):
            # for each row, get the last row and append and prepend with 0 
            temp = [0] + res[-1] + [0]
            # each row
            row = []
            # building the each row
            for j in range(len(res[-1]) + 1):
                row.append(temp[j] + temp[j+1])
            res.append(row)
        return res

More from this blog

yesicbap

437 posts