给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
对左右括号数目进行DFS。
当左括号数目<n,添加左括号
当右括号数目<左括号数目,添加右括号
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
# 记录左右括号的数量
def dfs(n,l,r,curr,res):
if len(curr)==2*n:
res.append(curr)
return
if l<n:dfs(n,l+1,r,curr+'(',res)
if l>r:dfs(n,l,r+1,curr+')',res)
res=[]
dfs(n,0,0,'',res)
return res