-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22 Generate Parentheses.py
More file actions
37 lines (27 loc) · 1.07 KB
/
Copy path22 Generate Parentheses.py
File metadata and controls
37 lines (27 loc) · 1.07 KB
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
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
stack = [] # for building combinations
results = [] # store all combinations
def recurse(amountOpen,amountClosed):
# base case
if n == amountOpen == amountClosed:
results.append("".join(stack))
return
# case: only add open pars when its less than n
if amountOpen < n:
stack.append('(')
recurse(amountOpen + 1,amountClosed)
stack.pop()
# case: only add closing pars when amountClosed less than amountOpen
if amountClosed < amountOpen:
stack.append(')')
recurse(amountOpen,amountClosed + 1)
stack.pop()
recurse(0,0)
return results
'''
stack to track our parenthese being built
need to track amount open and closed
- n = amount max open = amount max clsing pars
backtracking/recursion to build up the combinations
'''