-
Notifications
You must be signed in to change notification settings - Fork 0
/
022. Generate Parentheses
43 lines (33 loc) · 1.08 KB
/
022. Generate Parentheses
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
#!/usr/bin/env python3
__author__ = 'Wei Mu'
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 0:
return [""]
left = n - 1
right = n
ans = ['(']
return (self.helper_func(ans, left, right))
def helper_func(self, ans, left, right):
if left == 0 and right == 0:
return(ans)
elif left == 0:
for i in range(len(ans)):
ans[i] = ans[i] + right * ')'
return(ans)
elif left == right:
for i in range(len(ans)):
ans[i] = ans[i] + '('
return(self.helper_func(ans, left - 1, right))
else:
temp1 = []
temp2 = []
for i in range(len(ans)):
temp1.append(ans[i] + '(')
temp2.append(ans[i] + ')')
ans = self.helper_func(temp1, left - 1, right) + self.helper_func(temp2, left, right - 1)
return(ans)