暴力解法:生成所有组合,然后校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
var generateParenthesis = function (n) { let res = []; function check(path) { const stack = []; for (let i = 0; i < path.length; i++) { const top = stack.length > 0 ? stack[stack.length - 1] : ""; if (top === "(" && path[i] === ")") { stack.pop(); } else { stack.push(path[i]); } } return !stack.length; } function generate(count, path) { if (count > 0) { for (const char of ["(", ")"]) { generate(count - 1, char + path); } } else { check(path) && res.push(path); } } generate(2 * n, ""); return res; }; console.log(generateParenthesis(3));
|
回溯,保证前缀合法的情况,继续前进
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
var generateParenthesis = function (n) { let res = []; function backtrack(cur = "", open = 0, close = 0) { if (cur.length === 2 * n) { res.push(cur); return; } if (open < n) { backtrack(cur + "(", open + 1, close); } if (close < open) { backtrack(cur + ")", open, close); } } backtrack(); return res; };
|
open<n
的情况下可以继续加左括号,close<open
的情况下,可以加右括号去闭合前面的左括号,直到所有括号都用完