2021-02-12

2021-02-12 Leetcode每日刷题

题目

Given an integer rowIndex, return the rowIndexth row of the Pascal’s triangle.
Notice that the row index starts from 0.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

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

Example 1:

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

Constraints:

0 <= rowIndex <= 33

我的思路
基本思路是写出第j行第i个数的表达式。第0个数和第j+1个数都为1,其余的值为第j-1行第i-1个数和第i个数的和。据此写出以下代码:

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        k = rowIndex
        Pascal = [] 
        for j in range(0,k+1):
            krow = []
            for i in range(j):
                if i == 0:
                    krow.append(1)
                else:
                    val = Pascal[j-1][i-1]+Pascal[j-1][i]
                    krow.append(val)
            krow.append(1)
            print(krow)
            Pascal.append(krow)
        print(Pascal[k])
        return Pascal[k]



你可能感兴趣的:(leetcode)