LeetCode-in-TypeScript.github.io

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

function generateParenthesis(n: number): string[] {
    const sb: string[] = []
    const ans: string[] = []
    return generate(sb, ans, n, n)
}

function generate(sb: string[], str: string[], open: number, close: number): string[] {
    if (open === 0 && close === 0) {
        str.push(sb.join(''))
        return str
    }
    if (open > 0) {
        sb.push('(')
        generate(sb, str, open - 1, close)
        sb.pop()
    }
    if (close > 0 && open < close) {
        sb.push(')')
        generate(sb, str, open, close - 1)
        sb.pop()
    }
    return str
}

export { generateParenthesis }