题意:

image.png

解题思路:

  1. 思路:
  2. 1. 递归左右括号;
  3. 2. 每次新增左括号的数目不能超过n
  4. 3. 每次新增右括号的数目不能超过n,并且左括号要大于右括号的数量;

PHP代码实现:

  1. class Solution {
  2. public $list = [];
  3. function generateParenthesis($n) {
  4. $this->generate(0, 0, $n, "");
  5. return $this->list;
  6. }
  7. function generate($left, $right, $n, $s) {
  8. if ($left == $n && $right == $n) {
  9. $this->list[] = $s;
  10. return;
  11. }
  12. if ($left < $n) $this->generate($left + 1, $right, $n, $s. "(");
  13. if ($right < $n && $left > $right) $this->generate($left, $right + 1, $n, $s. ")");
  14. }
  15. }

GO代码实现:

  1. func generateParenthesis(n int) []string {
  2. result := make([]string, 0)
  3. generate("", 0, 0, n, &result)
  4. return result
  5. }
  6. func generate(current string, left, right, n int, result *[]string) {
  7. if left == n && right == n {
  8. *result = append(*result, current)
  9. return
  10. }
  11. if left < n {
  12. generate(current + "(", left + 1, right, n, result)
  13. }
  14. if right < n && left > right {
  15. generate(current + ")", left, right + 1, n, result)
  16. }
  17. }