Pascal's Triangle
题目描述
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]
]
解题方法
这一题和triangle类似,每一层元素是它上面两个元素的和
Solution
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
result = [[1]]
if numRows == 1:
return result
cur = [1]
for i in range(1, numRows):
tmp = [0 for i in range(i+1)]
for j in range(i+1):
if j == 0:
tmp[0] = 1
elif j == i:
tmp[j] = 1
else:
tmp[j] = cur[j-1] + cur[j]
result.append(tmp)
cur = list(tmp)
return result