-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.py
More file actions
39 lines (30 loc) · 810 Bytes
/
22.py
File metadata and controls
39 lines (30 loc) · 810 Bytes
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
"""
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]"""
class Solution:
def generateParenthesis(self, n):
"""
:param n: int
:return: list[str]
"""
res = []
def back(tmp, left, right, n):
if left == n:
tmp += ')' * (left - right)
res.append(tmp)
return
if left < n:
back(tmp + '(', left + 1, right, n)
if right < left:
back(tmp + ')', left, right + 1, n)
back('', 0, 0, n)
return res
s = Solution()
print(s.generateParenthesis(2))