Skip to content
On this page

22. 括号生成

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

示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:
输入:n = 1
输出:["()"]

提示:
1 <= n <= 8

javascript
/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function(n) {
  const res = []
  dfs(n, n, '', res)
  return res
}

function dfs(left, right, str, res) {
  if (left === 0 && right === 0) {
    res.push(str)
    return
  }
  if (left > 0) {
    dfs(left - 1, right, str + '(', res)
  }
  if (right > left) {
    dfs(left, right - 1, str + ')', res)
  }
}

console.log(generateParenthesis(3))
console.log(generateParenthesis(2))
console.log(generateParenthesis(1))