-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0022.py
More file actions
44 lines (34 loc) · 1.29 KB
/
0022.py
File metadata and controls
44 lines (34 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
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
memory = {
"(": n,
")": n
}
answers = set()
def recurse(string, memory, answers):
# print(string, memory)
if len(string) == n * 2:
if self.is_valid(string):
answers.add(string)
elif len(string) < n * 2:
left_counter = memory["("]
if left_counter > 0:
recurse(string + "(", {"(": memory["("] - 1, ")": memory[")"]}, answers)
right_counter = memory[")"]
if right_counter > 0:
recurse(string + ")", {")": memory[")"] - 1, "(": memory["("]}, answers)
recurse("", memory, answers)
return answers
def is_valid(self, string):
if len(string) % 2 != 0:
return False
stack = []
for i in range(len(string)):
if string[i] == "(":
stack.append(string[i])
else:
if not stack:
return False
elif stack.pop() != "(":
return False
return True if not stack else False