📑 题目:22. 括号生成

🚀 本题 LeetCode 传送门

题目大意

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

解题思路

  • 这道题乍一看需要判断括号是否匹配的问题,如果真的判断了,那时间复杂度就到 O(n * 2^n)了,虽然也可以 AC,但是时间复杂度巨高。
  • 这道题实际上不需要判断括号是否匹配的问题。因为在 DFS 回溯的过程中,会让 () 成对的匹配上的。

代码

  1. package leetcode
  2. func generateParenthesis(n int) []string {
  3. if n == 0 {
  4. return []string{}
  5. }
  6. res := []string{}
  7. findGenerateParenthesis(n, n, "", &res)
  8. return res
  9. }
  10. func findGenerateParenthesis(lindex, rindex int, str string, res *[]string) {
  11. if lindex == 0 && rindex == 0 {
  12. *res = append(*res, str)
  13. return
  14. }
  15. if lindex > 0 {
  16. findGenerateParenthesis(lindex-1, rindex, str+"(", res)
  17. }
  18. if rindex > 0 && lindex < rindex {
  19. findGenerateParenthesis(lindex, rindex-1, str+")", res)
  20. }
  21. }