Generate Parentheses in TypeScript

function generateParenthesis(n: number): string[] {
    let result: string[] = [];

    function backtrack(s: string, open: number, close: number) {
        // Base case: if the string is of the correct length, add to result
        if (s.length === 2 * n) {
            result.push(s);
            return;
        }

        // If the number of open parentheses is less than n, add an open parenthesis
        if (open < n) {
            backtrack(s + '(', open + 1, close);
        }

        // If the number of close parentheses is less than open ones, add a close parenthesis
        if (close < open) {
            backtrack(s + ')', open, close + 1);
        }
    }

    // Start the recursion with an empty string and both counts as 0
    backtrack('', 0, 0);

    return result;
}

PrevNext