数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
递归
首先是括号不匹配版本的,在 webstorm 里面跑了一下。
对于递归来说,最重要的还是 1. recursion terminator ; 2. process data in current logic ; 3. drill down to the next level; 4. reverse if needed
var main = function () {
console.log(generateParenthesis(3));
};
var generateParenthesis = function (n) {
_generate(0, 2 * n, "");
};
var _generate = function (level, max, s) {
// terminator
if (level >= max) {
console.log(s);
return;
}
// process current logic: left, right
let s1 = s + "(";
let s2 = s + ")";
// drill down
_generate(level + 1, max, s1);
_generate(level + 1, max, s2);
// reverse states
};
main();
括号匹配的
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let res = [];
_generate(res, 0, 0, n, '');
return res;
};
var _generate = function(res, left, right, n, s) {
// terminator
if(left === n && right === n) {
res.push(s);
return s;
}
// process current
if(left < n) {
_generate(res, left + 1, right, n, s + '(');
}
if(left > right && right < n) {
_generate(res, left, right + 1, n, s + ')');
}
}