题目描述
给定一个非负整数 numRows
,生成杨辉三角的前 numRows
行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
迭代法
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows < 1:
return []
res = [[1]]
if numRows == 1:
return res
res.append([1, 1])
if numRows == 2:
return res
for i in range(3, numRows + 1):
res.append([1, *[res[-1][i] + res[-1][i + 1] for i in range(len(res[-1]) - 1)], 1])
return res
执行结果:通过
执行用时:48 ms, 在所有 Python3 提交中击败了13.88% 的用户
内存消耗:13.6 MB, 在所有 Python3 提交中击败了5.21% 的用户
一行解
参考了 typingMonkey 的题解:
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
return [[math.comb(i, j) for j in range(i + 1)] for i in range(numRows)]
执行结果:通过
执行用时:36 ms, 在所有 Python3 提交中击败了80.99% 的用户
内存消耗:13.6 MB, 在所有 Python3 提交中击败了7.03% 的用户
这里用到了数学知识以及 math.comb(n, k)
来求组合数,即从 n
个元素中任取 k
个元素,一共有多少种取法。
C n k = n ! k ! × ( n − k ) ! C_n^k = \frac{n!}{k! \times {(n - k)!}} Cnk=k!×(n−k)!n!
相关的帮助文档如下:
>>> import math
>>> help(math.comb)
Help on built-in function comb in module math:
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n.
Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.
顺带说一下,
math
模块中,math.perm
是用来求排列数的函数,之前还用到过求可迭代对象连乘的math.prod
。
以第 5
行的杨辉三角列表 [1, 4, 6, 4, 1]
为例,它恰好为:
[ C 4 0 , C 4 1 , C 4 2 , C 4 3 , C 4 4 ] [C_4^0, C_4^1, C_4^2, C_4^3, C_4^4] [C40,C41,C42,C43,C44]
所以第 i
行的杨辉三角列表为
C
i
−
1
j
C_{i - 1}^j
Ci−1j,其中
0
⩽
j
⩽
i
−
1
0 \leqslant j \leqslant i - 1
0⩽j⩽i−1。
2020.12.06