Lincode 1354. Pascal's Triangle II (Easy) (Python)

1354. Pascal’s Triangle II

Description:

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Example
Example:

Input: 3
Output: [1,3,3,1]
Challenge
Could you optimize your algorithm to use only O(k) extra space?

Code:

class Solution:
    """
    @param rowIndex: a non-negative index
    @return: the kth index row of the Pascal's triangle
    """
    def getRow(self, rowIndex):
        # write your code here
        def pascal(index, preRow):
            curRow = [1]
            for i in range(index-1):
                curRow.append(preRow[i]+preRow[i+1])
            curRow.append(1)
            return curRow
        secondRow = [1,1]
        tmpRow = secondRow
        if rowIndex == 1:
            return secondRow
        for i in range(2, rowIndex+1):
            tmpRow = pascal(i, tmpRow)
        return tmpRow

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/80979149