![]() |
VOOZH | about |
Given a number n, print all combinations of balanced parentheses of length n.
Note: A sequence of parentheses is balanced if every opening bracket ( has a corresponding closing bracket ) in the correct order.
Examples:
Input: n = 2
Output: ["( )"]
Explanation: Only one valid sequence can be formed using 1 pair of parentheses, and it is balanced.Input : n = 4
Output: [ "( ( ) )", "( )( )"]
Explanation: Two valid balanced sequences are possible with 2 pairs: one with nested parentheses, and one with pairs side by side.
Table of Content
The main idea is to generate all possible combinations of parentheses and check if it is balance or not. If a sequence is balanced, we store it as a valid result.
We recursively construct the sequence by considering these two conditions.
- The
i-th character can be '('if the number of opening '('brackets used so far is less thann. This ensures we don’t add more opening brackets than are needed, keeping the sequence valid.- The
i-th character can be ')' if the number of closing ')'brackets used so far is less than the number of opening '('brackets. This ensures that each closing bracket has a matching opening bracket before it, maintaining the balance.
(()) ()()
Time complexity: O(Cn × n), where Cn is the nth Catalan number.
('.(' has to match some closing ')' later. Suppose it matches the very next character then you’ve enclosed 0 other pairs inside, and the rest of the string (after that match) is a valid sequence of n − 1 pairs.( … )) ", and the remainder after is a valid sequence of n−2 pairs.If you let Ck be the number of sequences of k pairs, then for each choice of how many pairs you “enclose” inside the first match (call that k), you get
Ck × Cn−1−k
Summing over k = 0 to k = n-1 gives the Catalan recurrence
Cn = (k = 0 to n - 1) ∑ Ck × Cn−1−k
| k | Recurrence | Value |
|---|---|---|
| 0 | — | 1 |
| 1 | C0 | 1 |
| 2 | C0C1 + C0C1 = 1+1 | 2 |
| 3 | C0C2 + C1C1 + C2C0 = 2+1+2 | 5 |
| 4 | C0C3 + C1C2 + C2C1 + C3C0 = 5+2+2+5 | 14 |
Auxiliary space: O(n), for the recursion stack depth and the temporary string storing the current sequence.