https://leetcode-cn.com/problems/generate-parentheses/
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
const res = []
const dfs = (index, lRemain, rRemain, str) => {
if (str.length == 2 * n) res.push(str)
for(let i = index; i < n * 2; i++) {
if (lRemain > 0) { // 只要左括号有剩,就可以选它,然后继续做选择(递归)
dfs(i+1, lRemain - 1, rRemain, str + "(");
}
if (lRemain < rRemain) { // 右括号比左括号剩的多,才能选右括号
dfs(i+1, lRemain, rRemain - 1, str + ")"); // 然后继续做选择(递归)
}
}
}
dfs(0, n, n, '')
return res
};