Wednesday, June 11, 2014

LeetCode (Python): Pascal's Triangle II

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?

Solution:

class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        actualRow =[1]
        for row in range(0, rowIndex):
            previousRow = actualRow
            actualRow = [1]
            for i in range(1,len(previousRow)):
                actualRow.append(previousRow[i-1] + previousRow[i])
            actualRow.append(1)
        return actualRow

No comments :

Post a Comment