-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParenthesis.py
More file actions
46 lines (31 loc) · 1.29 KB
/
GenerateParenthesis.py
File metadata and controls
46 lines (31 loc) · 1.29 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
38
39
40
41
42
43
44
45
46
# Question Link - https://leetcode.com/problems/generate-parentheses/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
stack = [] #Store the single parenthesis
res = [] #res of the combination of valid parenthesis
def generate(openN , closeN):
if openN == closeN == n:
res.append("".join(stack))
return
if openN < n :
stack.append('(')
generate(openN + 1 , closeN)
stack.pop()
if closeN < openN :
stack.append(')')
generate(openN , closeN + 1)
stack.pop()
generate(0 , 0)
return res
# Solution 1
# ans = []
# self.generate(0 , 0 , n ,"" ,ans)
# return ans
# def generate(self, open_count , close_count , n , current , ans):
# if open_count == close_count == n:
# ans.append(current)
# return
# if open_count < n:
# self.generate(open_count + 1,close_count,n,current + '(',ans)
# if close_count < open_count:
# self.generate(open_count , close_count + 1, n, current + ')',ans)