forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pascals-triangle-ii.py
66 lines (56 loc) · 1.57 KB
/
pascals-triangle-ii.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Time: O(n^2)
# Space: O(1)
# Given an index k, return the kth row of the Pascal's triangle.
#
# For example, given k = 3,
# Return [1,3,3,1].
#
# Note:
# Could you optimize your algorithm to use only O(k) extra space?
#
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
result = [0] * (rowIndex + 1)
for i in xrange(rowIndex + 1):
old = result[0] = 1
for j in xrange(1, i + 1):
old, result[j] = result[j], old + result[j]
return result
def getRow2(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
row = [1]
for _ in range(rowIndex):
row = [x + y for x, y in zip([0] + row, row + [0])]
return row
def getRow3(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0: return [1]
res = [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 res[1] < rowIndex:
res = add(res)
return res
# Time: O(n^2)
# Space: O(n)
class Solution2:
# @return a list of integers
def getRow(self, rowIndex):
result = [1]
for i in range(1, rowIndex + 1):
result = [1] + [result[j - 1] + result[j] for j in xrange(1, i)] + [1]
return result
if __name__ == "__main__":
print Solution().getRow(3)