118. pascal’s triangle

Description

Difficulty: Easy

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]
]

题意:

给出行数,生成相应行帕斯卡三角。

Solution

帕斯卡三角的下一行的某元素是上一行的相邻两元素的和。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class (object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
rslt = []
elif numRows == 1:
rslt = [[1]]
elif numRows == 2:
rslt = [[1], [1, 1]]
elif numRows > 2:
rslt = [[1], [1, 1]]
for i in xrange(2, numRows):
now = [1]
for j in xrange(1, i):
now.append(rslt[i-1][j-1] + rslt[i-1][j])
now.append(1)
rslt.append(now)
return rslt