leetcode 刷題 118. 楊輝三角解題思路

給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。

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

示例:

輸入: 5
輸出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

解答:

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        result = [ [1] * (i+1) for i in range(numRows)]
        if numRows>=3:
            for i in range(2,numRows):
                for j in range(1,i):
                    result[i][j] = result[i-1][j-1] + result[i-1][j]
        return result

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章