forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-parentheses.py
43 lines (39 loc) · 1.22 KB
/
generate-parentheses.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(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
# iterative solution
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
stk = [("", n, n)]
while stk:
curr, left, right = stk.pop()
if left == 0 and right == 0:
result.append(curr)
if left < right:
stk.append((curr+")", left, right-1))
if left > 0:
stk.append((curr+"(", left-1, right))
return result
# Time: O(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
# recursive solution
class Solution2(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def generateParenthesisRecu(result, current, left, right):
if left == 0 and right == 0:
result.append(current)
if left > 0:
generateParenthesisRecu(result, current + "(", left-1, right)
if left < right:
generateParenthesisRecu(result, current + ")", left, right-1)
result = []
generateParenthesisRecu(result, "", n, n)
return result