1. 程式人生 > >Leetcode 119. 楊輝三角 II(Python3)

Leetcode 119. 楊輝三角 II(Python3)

119. 楊輝三角 II

給定一個非負索引 k,其中 k ≤ 33,返回楊輝三角的第 行。

在楊輝三角中,每個數是它左上方和右上方的數的和。

示例:

輸入: 3
輸出: [1,3,3,1]

進階:

你可以優化你的演算法到 O(k) 空間複雜度嗎?

 

程式碼:

class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        res = []
        for i in range(rowIndex+1):
            cr = [1]*(rowIndex+1)         
            if i > 1:
                for j in range(1,i):
                    cr[j] = res[j-1] + res[j]
            res = cr
        return res

 

大佬的兩種寫法:

class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        # method one
        # row = [1]
        # for i in range(1,rowIndex+1):
        #     row = list(map( lambda x,y : x+y , row + [0] , [0] + row )) 
        # return row        



        # method two    老土的方法,但有效,不用藉助高等函式map()
        res = [1]
        for i in range(1, rowIndex+1):
            res = [1] + [res[i] + res[i + 1] for i in range(len(res) - 1)] + [1]
        return res