括号。设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。
说明:解集不能包含重复的子集。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
一、递归
将下一对“()”插入f(n-1)的所有括号内;
用set去重。
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n<0: return []
if n==0: return ['']
res=set()
for s in self.generateParenthesis(n-1):
for i in range(2*n-1):
if s[:i]+'()'+s[i:] in res:
continue
res.add(s[:i]+'()'+s[i:])
return list(res)
二、回溯
l和r代表已使用左括号和右括号的数量;
当r>l时不符合括号规定,剪枝。
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
def f(l,r,s):
if l == r and r == n:
ans.append(s)
if l<n:
f(l+1,r,s+'(')
if r<l:
f(l,r+1,s+')')
f(0,0,'')
return ans