数字
n代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
解法 回溯
思路
递归参数肯定需要路径 path ,然后怎么去控制加左括号还是右括号呢?可以用两个计数器。
递归的规则就是如果当前左括号比 n 小,那么可以加左括号;如果当前左括号比右括号大,那么可以加右括号。
递归结束条件就是左右括号都等于 n。
代码
function generateParenthesis(n: number): string[] {
const result = [];
const dfs = (path, left, right) => {
if (left === n && right === n) {
result.push(path.join(""));
return;
}
if (left < n) {
path.push("(");
dfs(path, left + 1, right);
path.pop();
}
if (left > right) {
path.push(")");
dfs(path, left, right + 1);
path.pop();
}
};
dfs([], 0, 0);
return result;
};
时空复杂度
时间复杂度:O((4^n / sqrt(n)) * n)
空间复杂度:O(Cn * n)