forked from HuberTRoy/leetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.py
47 lines (35 loc) · 986 Bytes
/
GenerateParentheses.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
"""
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
生成有效的括号对。
关键字:
递归
beat
100%
测试地址:
https://leetcode.com/problems/generate-parentheses/description/
"""
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
def _generateParenthesis(x, y, parenthesis):
if not x and not y:
result.append(parenthesis)
return
if y > x:
_generateParenthesis(x, y-1, parenthesis=parenthesis+')')
if x:
_generateParenthesis(x-1, y, parenthesis=parenthesis+'(')
_generateParenthesis(n-1, n, '(')
return result