Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
根据杨辉三角的规律,发现最后一行可以由倒数第二行生成。因此,从第一行开始,逐次构造下一行,知道满足条件为止。
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
rlist = []
rlist.append([1]) # 第一行元素
i = 1
while i < numRows:
rlist.append([]) # 新增下一行
rlist[i].append(1)
j = 0
while j < len(rlist[i-1]) - 1: # 构造下一行元素
rlist[i].append(rlist[i-1][j] + rlist[i-1][j+1])
j += 1
rlist[i].append(1)
i += 1
return rlist
a = 5
b = Solution()
print(b.generate(a)) # [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]