leetcode -- Pascal's Triangle II -- 简单

https://leetcode.com/problems/pascals-triangle-ii/
杨辉三角的题目

class Solution(object):
    def getRow(self, rowIndex):
        """ :type rowIndex: int :rtype: List[int] """
        k = rowIndex + 1
        if k == 0:
            return []
        elif k == 1:
            return [1]
        elif k == 2:
            return [1,1]

        res = [1,1]
        for i in xrange(2, k):
            tmp = [1]
            for j in xrange(0, i-1):
                tmp.append(res[j] + res[j + 1])
            tmp.append(1)
            res = tmp
        return res

自己重写code,只用O(k) space

class Solution(object):
    def getRow(self, rowIndex):
        """ :type rowIndex: int :rtype: List[int] """
        res = [1]
        for i in xrange(rowIndex):
            j = len(res) - 1
            res.append(1)#在res后面加个1
            while j >=1:
                res[j]  = res[j] + res[j-1]
                j -= 1
                #res[0]不需要修改,反正就是1
        return res

你可能感兴趣的:(LeetCode)