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

在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5 输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1] ]
方法一
想法:如动图所示:i层j项为i-1层中第j项与第j-1项之和
故:
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows <= 0:
return []
if numRows == 1:
return [[1]]
list = [[1],[1,1]]
for i in range(2, numRows):
L = [1]
for j in range(1,i):
L.append(list[i-1][j-1]+list[i-1][j])
L.append(1)
list.append(L)
return list
方法二:
如第4层 1 3 3 1,就是C(0,3) C(1,3) C(2,3) C(3,3)
然后叠加保存即可。
参考自https://blog.csdn.net/weixin_40449071/article/details/81193354
实现每层代码如下:
from scipy.special import comb, perm
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = []
for i in range (0,rowIndex+1):
res.append(int(round(comb(rowIndex,i),0)))
return res
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
