Back to Parenthesis
Parenthesis
Medium

Generate Parentheses

LAB

Generate all well-formed parentheses strings containing n pairs, sorted lexicographically.

EXAMPLES

Example 1
Input
{
  "n": 3
}

Output
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

FUNCTION SHAPE

n: intstringArray
SOLUTION NOTE

Backtracking with pruning. Only add '(' if we have remaining, only add ')' if it won't exceed open count.

Reveal reference solution +
pythonREFERENCE
def generateParenthesis(self, n: int) -> List[str]:
    res = []

    def backtrack(curr, open_count, close_count):
        if len(curr) == 2 * n:
            res.append(''.join(curr))
            return

        if open_count < n:
            curr.append('(')
            backtrack(curr, open_count + 1, close_count)
            curr.pop()

        if close_count < open_count:
            curr.append(')')
            backtrack(curr, open_count, close_count + 1)
            curr.pop()

    backtrack([], 0, 0)
    return res
TimeO(4^n / sqrt(n))
SpaceO(n)
Open on LeetCode
00:00
2 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.