LeetCode-in-All

22. Generate Parentheses

Medium

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:

Solution

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function(n) {
    const result = [];
    
    const generate = (current, open, close) => {
        if (open === 0 && close === 0) {
            result.push(current);
            return;
        }
        if (open > 0) {
            generate(current + '(', open - 1, close);
        }
        if (close > 0 && open < close) {
            generate(current + ')', open, close - 1);
        }
    };

    generate('', n, n);
    return result;
};

export { generateParenthesis }