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

 

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