Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

    Example 1:
    Input: n = 3 Output: [“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
    Example 2:
    Input: n = 1 Output: [“()”]

    Constraints:

    • 1 <= n <= 8

    Accepted
    781,434
    Submissions
    1,168,852

    Runtime: 68 ms, faster than 96.95% of JavaScript online submissions for Generate Parentheses.
    Memory Usage: 40.4 MB, less than 32.27% of JavaScript online submissions for Generate Parentheses.

    1. /**
    2. * @param {number} n
    3. * @return {string[]}
    4. */
    5. var generateParenthesis = function(n) {
    6. const result = [];
    7. const max = n * 2;
    8. function backtrace(str, open, close) {
    9. if (str.length === max) {
    10. result.push(str);
    11. return;
    12. }
    13. if (open < n) {
    14. backtrace(str + '(', open + 1, close);
    15. }
    16. if (close < open) {
    17. backtrace(str + ')', open, close + 1);
    18. }
    19. }
    20. backtrace('', 0, 0);
    21. return result;
    22. };