数字
n代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的括号组合。示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
核心规则
- 左括号数量 ≤ n
- 右括号数量 不能超过 左括号(避免
)(非法) - 左右都用完就收集答案
python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def dfs(path, left, right):
if left == n and right == n:
res.append(path)
return
if left < n:
dfs(path + "(", left + 1, right)
if right < left:
dfs(path + ")", left, right + 1)
dfs("", 0, 0)
return res