[LeetCode] 119. 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:

Running Time: O(n2).

Space: O(n)

解法参照ALF的博客:http://blog.csdn.net/abcbc/article/details/8982651

‘’‘

1 0 0 0    k = 0

1 1 0 0    k = 1

1 1 1 0

1 2 1 0    k = 2

1 2 1 1

1 2 3 1

1 3 3 1    k = 3

上述过程实际上就是一个in-place的迭代过程。每当生成下一行的时候,首先数组相应位置1,然后从右向左计算每一个系数。

’‘’


class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        if rowIndex < 0:
            return []
        result = [0] * (rowIndex+1)
        for i in range(rowIndex+1):
            result[i] = 1
            for j in range(i-1, 0, -1):# from right to left, avoid redundant calculation/unclean data.
                result[j] = result[j] + result[j-1]
        return result




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