Skip to content

Commit 0138878

Browse files
committed
Pascal's Triangle/ Pascal's Triangle II
1 parent 02ee104 commit 0138878

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

118 Pascal's Triangle.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
Given numRows, generate the first numRows of Pascal's triangle.
3+
4+
For example, given numRows = 5,
5+
Return
6+
7+
[
8+
[1],
9+
[1,1],
10+
[1,2,1],
11+
[1,3,3,1],
12+
[1,4,6,4,1]
13+
]
14+
'''
15+
16+
class Solution(object):
17+
def generate(self, numRows):
18+
"""
19+
:type numRows: int
20+
:rtype: List[List[int]]
21+
"""
22+
if not numRows:
23+
return []
24+
result = [[1]]
25+
while numRows > 1:
26+
result.append([1] + [a + b for a, b in zip(result[-1][:-1], result[-1][1:])] + [1])
27+
numRows -= 1
28+
return result
29+
30+
31+
if __name__ == "__main__":
32+
assert Solution().generate(4) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]

119 Pascal's Triangle II.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'''
2+
Given an index k, return the kth row of the Pascal's triangle.
3+
4+
For example, given k = 3,
5+
Return [1,3,3,1].
6+
7+
Note:
8+
Could you optimize your algorithm to use only O(k) extra space?
9+
'''
10+
11+
class Solution(object):
12+
def getRow(self, rowIndex):
13+
"""
14+
:type rowIndex: int
15+
:rtype: List[int]
16+
"""
17+
result = [1] * (rowIndex + 1)
18+
for i in range(2, rowIndex + 1):
19+
for j in range(1, i):
20+
result[i - j] += result[i - j - 1]
21+
return result
22+
23+
24+
if __name__ == "__main__":
25+
assert Solution().getRow(3) == [1, 3, 3, 1]

0 commit comments

Comments
 (0)