var generateParenthesis = function (n) { let left = 0, right = 0, ans = [] const _generate = function (left, right, n, s) { if (left === n && right === n) { ans.push(s) return } if (left < n) _generate(left + 1, right, n, s + "(") if (left > right) _generate(left, right + 1, n, s + ")") } _generate(left, right, n, "") return ans }; console.log(generateParenthesis(3));