-
Notifications
You must be signed in to change notification settings - Fork 2
/
Generate-Parentheses.py
36 lines (31 loc) · 1.09 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
import itertools
class Solution(object):
def generateParenthesis(self, n):
self.max = (n * 2)
a = {')': '('}
self.vals = []
def is_valid(parenString):
stack = []
for letter in parenString:
if (len(stack) == 0):
stack.append(letter)
elif (stack[(-1)] == a.get(letter)):
stack.pop((-1))
else:
stack.append(letter)
return (len(stack) == 0)
vals = (['(' for i in range(n)] + [')' for i in range(n)])
def create(n, stack=['('], val='', left=None):
if (left == None):
left = vals
left.remove(stack[(-1)])
val += stack[(-1)]
if (len(val) == self.max):
if (is_valid(val) == True):
self.vals.append(val)
if (')' in left):
create(n, (stack + [')']), val, list(left))
if ('(' in left):
create(n, (stack + ['(']), val, list(left))
create(n)
return self.vals