数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
回溯
python
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res_list = []
self.backtrack(n, n, res_list, [])
return res_list
def backtrack(self, left, right, res_list, res):
if left + right == 0:
res_list.append("".join(res))
else:
if left == right:
left -= 1
res.append('(')
self.backtrack(left, right, res_list, res)
res.pop()
left += 1
else:
if left > 0:
left -= 1
res.append('(')
self.backtrack(left, right, res_list, res)
res.pop()
left += 1
if right > 0:
right -= 1
res.append(')')
self.backtrack(left, right, res_list, res)
res.pop()
right += 1