119. Pascal's triangle II Leetcode Python

Given an index k, return the kth row of the Pascal's triangle.


For example, given k = 3,
Return [1,3,3,1].


Note:

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

这题和前面一题的区别在于不用返回所有解,只需要返回index对应行就行。做法和前面的一样定义一个currow 和prerow


class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        rownum=rowIndex+1
        currow=[1]
        if rownum==1:
            return currow
        if rownum>0:
            currow=[1]
            for index in range(rownum):
                prerow=currow
                currow=[1]
                for j in range(index-1):
                    currow.append(prerow[j]+prerow[j+1])
                currow.append(1)
        return currow


你可能感兴趣的:(LeetCode,array,python)