## 22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

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


b'
\n\n

#### Approach #1: Brute Force [Accepted]

\n

Intuition

\n

We can generate all sequences of \'(\' and \')\' characters. Then, we will check if each one is valid.

\n

Algorithm

\n

To generate all sequences, we use a recursion. All sequences of length n is just \'(\' plus all sequences of length n-1, and then \')\' plus all sequences of length n-1.

\n

To check whether a sequence is valid, we keep track of balance, the net number of opening brackets minus closing brackets. If it falls below zero at any time, or doesn\'t end in zero, the sequence is invalid - otherwise it is valid.

\n\n

Complexity Analysis

\n
\n
• \n

Time Complexity : . For each of sequences, we need to create and validate the sequence, which takes work.

\n
• \n
• \n

Space Complexity : . Naively, every sequence could be valid. See Approach #3 for development of a tighter asymptotic bound.

\n
• \n
\n
\n

#### Approach #2: Backtracking [Accepted]

\n

Intuition and Algorithm

\n

Instead of adding \'(\' or \')\' every time as in Approach #1, let\'s only add them when we know it will remain a valid sequence. We can do this by keeping track of the number of opening and closing brackets we have placed so far.

\n

We can start an opening bracket if we still have one (of n) left to place. And we can start a closing bracket if it would not exceed the number of opening brackets.

\n\n

Complexity Analysis

\n

Our complexity analysis rests on understanding how many elements there are in generateParenthesis(n). This analysis is outside the scope of this article, but it turns out this is the n-th Catalan number , which is bounded asymptotically by .

\n
\n
• \n

Time Complexity : . Each valid sequence has at most n steps during the backtracking procedure.

\n
• \n
• \n

Space Complexity : , as described above, and using space to store the sequence.

\n
• \n
\n
\n

#### Approach #3: Closure Number [Accepted]

\n

Intuition

\n

To enumerate something, generally we would like to express it as a sum of disjoint subsets that are easier to count.

\n

Consider the closure number of a valid parentheses sequence S: the least index >= 0 so that S, S, ..., S[2*index+1] is valid. Clearly, every parentheses sequence has a unique closure number. We can try to enumerate them individually.

\n

Algorithm

\n

For each closure number c, we know the starting and ending brackets must be at index 0 and 2*c + 1. Then, the 2*c elements between must be a valid sequence, plus the rest of the elements must be a valid sequence.

\n\n

Complexity Analysis

\n
\n
• Time and Space Complexity : . The analysis is similar to Approach #2.
• \n
\n
\n

Analysis written by: @awice. Approach #2 inspired by @brobins9.

\n
'