Skip to content

Commit fc73c29

Browse files
committed
括号合法组合问题(dfs简单)
1 parent c6e26cc commit fc73c29

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# coding: utf8
2+
3+
4+
"""
5+
题目链接: https://leetcode.com/problems/generate-parentheses/description.
6+
题目描述:
7+
8+
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
9+
10+
For example, given n = 3, a solution set is:
11+
12+
[
13+
"((()))",
14+
"(()())",
15+
"(())()",
16+
"()(())",
17+
"()()()"
18+
]
19+
20+
"""
21+
22+
23+
class Solution(object):
24+
def generateParenthesis(self, n):
25+
"""
26+
:type n: int
27+
:rtype: List[str]
28+
"""
29+
if n < 0:
30+
return []
31+
elif n == 0:
32+
return ['']
33+
34+
ans = []
35+
self.backtrack(n, 1, 0, '(', ans)
36+
37+
return ans
38+
39+
def backtrack(self, n, lc, rc, cur, ans):
40+
# 保证每个状态下, 左括号出现次数不低于右括号
41+
if lc < rc or max(lc, rc) > n:
42+
return
43+
elif lc == n and rc == n:
44+
ans.append(cur)
45+
else:
46+
self.backtrack(n, lc + 1, rc, cur + '(', ans)
47+
self.backtrack(n, lc, rc + 1, cur + ')', ans)

0 commit comments

Comments
 (0)