118 杨辉三角

本文最后更新于:2022年4月9日 中午


给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

img

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

1
2
3
4
5
6
7
8
9
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

Solution

  • 每次初始化一个大小为 i+1 的数组,初始值为1。
  • 结果用一个二维数组存储,从第三行开始对数组默认元素值进行修改。
1
2
3
4
5
6
7
8
9
10
11
12
# @lc code=start
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = []
for i in range(numRows):
row = [1]*(i+1)
if i >= 2:
for j in range(1,i):
row[j] = result[i-1][j-1] + result[i-1][j]
result.append(row)
return result
# @lc code=end

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!