Skip to content

Commit b97bedc

Browse files
Add No_119: Pascal's Triangle II
1 parent 8de2373 commit b97bedc

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'''
2+
3+
Description:
4+
5+
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
6+
7+
Note that the row index starts from 0.
8+
9+
In Pascal's triangle, each number is the sum of the two numbers directly above it.
10+
11+
Example:
12+
13+
Input: 3
14+
Output: [1,3,3,1]
15+
Follow up:
16+
17+
Could you optimize your algorithm to use only O(k) extra space?
18+
19+
'''
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
'''
2+
3+
Description:
4+
5+
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
6+
7+
Note that the row index starts from 0.
8+
9+
In Pascal's triangle, each number is the sum of the two numbers directly above it.
10+
11+
Example:
12+
13+
Input: 3
14+
Output: [1,3,3,1]
15+
Follow up:
16+
17+
Could you optimize your algorithm to use only O(k) extra space?
18+
19+
'''
20+
21+
22+
from math import factorial
23+
from typing import List
24+
25+
class Solution:
26+
27+
def comb(self, n, m):
28+
29+
if n == m or m == 0:
30+
return 1
31+
else:
32+
return factorial(n) // ( factorial(m) * factorial(n-m) )
33+
34+
35+
def getRow(self, rowIndex: int) -> List[int]:
36+
37+
# the coefficient of level k is as folling
38+
#
39+
# C(k,0), C(k,1), ... , C(k,k)
40+
41+
return [ self.comb(rowIndex,i) for i in range(0, rowIndex+1) ]
42+
43+
44+
45+
# k : the input value of rowIndex
46+
47+
## Time Complexity: O( k )
48+
#
49+
# The major overhead in time is the length of list comprehension on i, which is of O( k )
50+
51+
## Space Complexity: O( k )
52+
#
53+
# The major overhead in space is the storge for output list, which is of O( k )
54+
55+
56+
57+
58+
def test_bench():
59+
60+
test_data = [ 0, 1, 2, 3, 4, 5 ]
61+
62+
# expected output:
63+
'''
64+
[1]
65+
[1, 1]
66+
[1, 2, 1]
67+
[1, 3, 3, 1]
68+
[1, 4, 6, 4, 1]
69+
[1, 5, 10, 10, 5, 1]
70+
'''
71+
72+
for n in test_data:
73+
74+
print( Solution().getRow(n) )
75+
76+
return
77+
78+
79+
80+
if __name__ == '__main__':
81+
82+
test_bench()

0 commit comments

Comments
 (0)