数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
javascript
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let res = [],path='',close=0,open=0
dps(res,path,close,open,n)
return res
};
let dps = function(res,path,close,open,n){
if (open>n||close>open) {
return
}
if (path.length==2*n) {
res.push(path)
}
dps(res,path+"(",close,open+1,n)
dps(res,path+")",close+1,open,n)
}
console.log(generateParenthesis(3));