-
注意dfs分出来写,
-
然后dfs 递归终止条件是什么,
-
然后需要记录当前分支状态,递归的时候传进去
-
然后需要记录当前结果状态,递归的时候传进去
-
深入条件是:
- 左括号大于0,然后就
- 右括号大于0,并且剩余左括号比右括号少。[左括号用的多,相等的话不行,因为递归进去,右括号该多了]
class Solution:
def generateParenthesis(self, n: int):
# def generateParenthesis(self, n: int) -> List[str]:
# leetcode submit region end(Prohibit modification and deletion)
ans = []
self.dfs(n, n, ans, '') # 左右括号、ans结果、cur结果
return ans
def dfs(self, left, right, ans, cur):
if not left and not right:
ans.append(cur)
if left:
self.dfs(left - 1, right, ans, cur + '(')
if right and left < right:
self.dfs(left, right - 1, ans, cur + ')')