给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
方案一:给通过给i-1行左右补组0,然后列表解析的方式一步到位得到第i行
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
l = [1]
l2 = []
i = 0
while i < numRows:
l2.append(l)
l = [sum(t) for t in zip([0]+l, l+[0])]
i += 1
return l2
方案二:常规思路,找出规律
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
if numRows == 1:
return [[1]]
res = [[1], [1, 1]]
for i in range(2, numRows):
a = [0] * (i + 1)
a[0], a[i] = 1, 1
for j in range(1, i):
a[j] = res[i - 1][j - 1] + res[i - 1][j]
res.append(a)
return res