标签:date 回溯法 javascrip keep return UNC code 多重 generate
生成多重括号,使用回溯法试探所有组合
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;
}
leetcode 22. Generate Parentheses
标签:date 回溯法 javascrip keep return UNC code 多重 generate
原文地址:https://www.cnblogs.com/rubylouvre/p/12041722.html