22.go 520 B

12345678910111213141516171819202122232425262728
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func generateParenthesisIter(last string, left, right, goal int, res *[]string) {
  6. if right == goal {
  7. *res = append(*res, last)
  8. return
  9. }
  10. if left < goal {
  11. generateParenthesisIter(last+"(", left+1, right, goal, res)
  12. }
  13. if right < left {
  14. generateParenthesisIter(last+")", left, right+1, goal, res)
  15. }
  16. }
  17. func generateParenthesis(n int) []string {
  18. res := &[]string{}
  19. generateParenthesisIter("", 0, 0, n, res)
  20. return *res
  21. }
  22. func main() {
  23. fmt.Println(generateParenthesis(3))
  24. }