forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPascals_Triangle.py
48 lines (43 loc) · 1.09 KB
/
Pascals_Triangle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
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:
# @return a list of lists of integers
def generate(numRows):
return self.generate_1(numRows)
def generate_1(self, numRows):
res = []
for j in range(numRows):
current = [1]
for i in range(1, j):
current.append(res[-1][i]+res[-1][i-1])
if j>=1:
current.append(1)
res.append(current[:])
return res
def generate_2(self, numRows):
if numRows ==0:
return []
if numRows == 1:
return [[1]]
if numRows == 2:
return [[1],[1,1]]
res = [[1], [1,1]]
prev = [1,1]
for j in range(numRows-1):
current = [1]
for i in range(1,len(prev)):
current.append(prev[i]+prev[i-1])
current.append(1)
res.append(current[:])
prev = current
return res