一、22. 括号生成
1.1、题目描述
1.2.1、回溯
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
ans = []
self.__dfs('', ans, 0, 0, n)
return ans
def __dfs(self, s: str, ans: List[str], left: int, right: int, n: int) -> None:
if 2*n == len(s):
ans.append(s)
return
if left < n:
self.__dfs(s+'(', ans, left+1, right, n)
# 右括号数目必须小于左括号数目
if right < left:
self.__dfs(s+')', ans, left, right+1, n)