-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22_Generate_Parentheses.py
85 lines (65 loc) · 1.83 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
22. Generate Parentheses
Medium
4422
241
Add to List
Share
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Accepted
495,384
Submissions
818,489
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def generateAll(s=[]):
if len(s) == 2*n:
if isValid(s):
res.append(''.join(s))
else:
s.append('(')
generateAll(s)
s.pop()
s.append(')')
generateAll(s)
s.pop()
def isValid(s):
bal = 0
for p in s:
if p == '(':
bal += 1
else:
bal -= 1
if bal < 0:
return False
return bal == 0
res = []
generateAll()
return res
def backtracking(s, cnt_l, cnt_r):
if len(s) == 2*n:
res.append(s)
if cnt_l < n:
backtracking(s+'(', cnt_l+1, cnt_r)
if cnt_r < cnt_l:
backtracking(s+')', cnt_l, cnt_r+1)
res = []
backtracking('(', 1, 0)
return res
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return ['']
res = []
for c in range(n):
for pairs_l in self.generateParenthesis(c):
for pairs_r in self.generateParenthesis(n-1-c):
res.append('({}){}'.format(pairs_l, pairs_r))
return res