方法:回溯
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
def dfs(path, left, right, n):
if left == n and right == n:
res.append(path)
if left < right:
return
if left < n:
dfs(path + '(', left+1, right, n)
if right < n:
dfs(path + ')', left, right+1, n)
dfs('', 0, 0, n)
return res