Skip to content

Commit a5b7dd5

Browse files
committed
added 0118_pascals_triangle.py
1 parent f3ad52c commit a5b7dd5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

easy/0118_pascals_triangle.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Given an integer numRows, return the first numRows of Pascal's triangle.
3+
4+
In Pascal's triangle, each number is the sum of the two numbers directly
5+
above it as shown:
6+
7+
Example 1:
8+
Input: numRows = 5
9+
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
10+
11+
Example 2:
12+
Input: numRows = 1
13+
Output: [[1]]
14+
15+
Constraints:
16+
* 1 <= numRows <= 30
17+
"""
18+
19+
class Solution:
20+
# O(n^2) solution, iterative
21+
#def generate(self, numRows: int) -> List[List[int]]:
22+
# out = [[1]]
23+
# for i in range(numRows - 1):
24+
# prev = out[-1]
25+
# curr = [prev[0]]
26+
#
27+
# for j in range(1, len(prev)):
28+
# curr.insert(j, prev[j] + prev[j-1])
29+
#
30+
# curr.append(prev[-1])
31+
# out.append(curr)
32+
#
33+
# return out
34+
35+
# O(n^2) solution, recursive
36+
def generate(self, numRows: int) -> List[List[int]]:
37+
if numRows == 1:
38+
return [[1]]
39+
40+
res = self.generate(numRows - 1)
41+
42+
prev = res[-1]
43+
curr = [prev[0]]
44+
for i in range(1, len(prev)):
45+
curr.insert(i, prev[i] + prev[i-1])
46+
curr.append(prev[-1])
47+
48+
return res + [curr]
49+

0 commit comments

Comments
 (0)