-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22-generate-parentheses.py
57 lines (49 loc) · 1.41 KB
/
22-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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
class Solution(object):
def backtrack(self, left, right, valid):
if not left and not right:
self.ans.append("".join(valid))
else:
if len(left) == len(right):
valid += left.pop()
self.backtrack(left, right, valid)
valid.pop()
left.append('(')
else:
for c in "()":
if c == '(' and left:
left.pop()
elif c == ')' and right:
right.pop()
else:
continue
valid += c
self.backtrack(left, right, valid)
valid.pop()
if c == '(':
left.append(c)
else:
right.append(c)
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
self.ans = []
left = ['('] * n
right = [')'] * n
valid = []
self.backtrack(left, right, valid)
return self.ans
if __name__ == "__main__":
print(Solution().generateParenthesis(3))