题目:
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
我的解法:顾名思义,一行一行求row,再append起来
class Solution:
def generate(self, numRows):
if numRows == 0:
return []
rows = []
rows.append([1])
for i in range(1, numRows):
row = []
row.append(1)
for j in range(1,i):
row.append(rows[i-1][j-1] + rows[i-1][j])
row.append(1)
rows.append(row)
return rows
别人的解法1:
explanation: Any row can be constructed using the offset sum of the previous row.
Example:
1 3 3 1 0
+ 0 1 3 3 1
= 1 4 6 4 1
def generate(self, numRows):
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]
法2: 运用杨辉三角的公式,比方第五行的数是:C(4,0) C(4,1) C(4,2) C(4,3) C(4,4)