题目链接
描述:给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。
例如,给出n=3,解集为:
“((()))”, “(()())”, “(())()”, “()()()”, “()(())”
思路:
回溯左子树不断添加‘(’,右子树不断添加 ‘)’。但为了保证合法,必须每个节点的左括号数量都大于右括号。因此用两个数记录左右子树的左括号个数和右括号个数
代码:
# 使用回溯递归,加左括号,然后加右括号
res = []
def dfs(n,left, right,path_str):
if left==n and right == n:
print(path_str)
res.append(path_str)
return
if left < n:
dfs(n,left+1, right, path_str+"(")
if right < left and right <n:
dfs(n, left, right+1,path_str+')')
class Solution:
#
def generateParenthesis(self , n: int) -> List[str]:
# write code here
dfs(n,0,0,"")
return res



![[LeetCode-Python版]21. 合并两个有序链表(迭代+递归两种解法)](https://i-blog.csdnimg.cn/direct/6ec2d456d9b5446f96ac063901349d31.png)













![[C++]C++工具之对异常情况的处理(throw、catch、try)以及用命名空间避免同名冲突](https://i-blog.csdnimg.cn/direct/b7960c80d26049f181852b9483e10048.png)

