[Solved] Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal’s triangle. In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

Table of Contents

Question

Given an integer rowIndex, return the rowIndexth (0-indexed) row of the 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: rowIndex = 3
Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
Output: [1]

Example 3:

Input: rowIndex = 1
Output: [1,1]

Constraints:

  • 0 <= rowIndex <= 33

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?

Python Solution

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

Leave a Reply

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