LeetCode #22 - Generate Parentheses (JavaScript)

From the root level, we always have two options to do:

  • open a brace if we didn't reach n
  • close the brace if we have left still opened

So this is what algorithm is focusing on.

const generateParenthesis = n => {
    const result = [];
    
    const generate = (str, left, right) => {
        if (str.length === n * 2) {
            return result.push(str);
        }
        
        if (left < n) {
            generate(str + '(', left + 1, right);
        }
        
        if (right < left) {
            generate(str + ')', left, right + 1);
        }
    }
    
    generate('', 0, 0);
    
    return result;
}