题目链接:https://leetcode-cn.com/problems/generate-parentheses/
难度:中等

描述:
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

提示:
n[1, 8]

题解

  1. class Solution:
  2. def generateParenthesis(self, n: int) -> List[str]:
  3. ret = []
  4. def dfs(temp, left, right):
  5. """
  6. temp:当前的括号串
  7. left:还有left个左括号没用
  8. right:还有right个右括号没用
  9. """
  10. if left == 0 and right == 0:
  11. ret.append(temp)
  12. return
  13. if left > right: # 当前括号串的左括号数必须比右括号数大,否则会出现未匹配的右括号
  14. return
  15. if left > 0:
  16. dfs(temp+'(', left-1, right)
  17. if right > 0:
  18. dfs(temp+')', left, right-1)
  19. dfs("", n, n)
  20. return ret