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]
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
这道题是构造pascal 三角形主要是要建立一个prerow 一个currow 然后每次下一行的除了开始以及结束的位置,中间位置currow.append(prerow[pos]+prerow[pos+1])最后再在最后补一个1
we need to define a prerow and currow everytime we add 1 to currow first and close it with 1, beside that currow.append(prerow[pos]+prerow[pos+1])
the code is as follow:
class Solution:
# @return a list of lists of integers
def generate(self, numRows):
solution=[]
if numRows==0:
return solution
if numRows>0:
actualrow=[1]
solution.append(actualrow)
for index in range(1,numRows):
prerow=actualrow
actualrow=[1]
for j in range(0,index-1):
actualrow.append(prerow[j]+prerow[j+1])
actualrow.append(1)
solution.append(actualrow)
return solution