生成多重括号,使用回溯法试探所有组合
function generateParenthesis(n) {
// Write your code here
var res = [], condidate = []
function backtrack(n, left, right) {
if (condidate.length == n * 2) {
res.push(condidate.join(''));
}
if (left < n) { //Keep 塞左括号
condidate.push('(');
backtrack(n, left + 1, right);
condidate.pop();
}
if (right < left) { //避免出现右括号多余左括号的情况
condidate.push(')');
backtrack(n, left, right + 1);
condidate.pop();
}
}
backtrack(n, 0, 0);
return res;
}