[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:

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:

Machine Learning Projects

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

Leave a Reply

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