forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpascals-triangle.py
44 lines (38 loc) · 1.19 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
# Time: O(n^2)
# Space: O(1)
class Solution(object):
# @return a list of lists of integers
def generate(self, numRows):
result = []
for i in xrange(numRows):
result.append([])
for j in xrange(i + 1):
if j in (0, i):
result[i].append(1)
else:
result[i].append(result[i - 1][j - 1] + result[i - 1][j])
return result
def generate2(self, numRows):
if not numRows: return []
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]
def generate3(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0: return []
if numRows == 1: return [[1]]
res = [[1], [1, 1]]
def add(nums):
res = nums[:1]
for i, j in enumerate(nums):
if i < len(nums) - 1:
res += [nums[i] + nums[i + 1]]
res += nums[:1]
return res
while len(res) < numRows:
res.extend([add(res[-1])])
return res