Generate all Combinations of Balanced Parentheses
Generate all combinations of balanced parentheses for the n number of parentheses pairs.
We'll cover the following...
We'll cover the following...
Statement
Write a function to generate all balanced combinations of pairs of parentheses.
Example
Here are a few examples:
The test cases will use values of in the range of 1 to 6.
Sample input
3
Expected output
{{{}}}
{{}{}}
{{}}{}
{}{{}}
{}{}{}
Try it yourself
Solution
The solution is to keep track of the number of opening and closing parentheses. We’ll use this count to add parentheses in a way that keeps the sequence valid.
- We only add an opening parenthesis if there is still one to add.
- We only add a closing parenthesis if its count does not exceed the number of opening parentheses.
The basic algorithm is as follows:
open_braces count: 0
close_braces count: 0
if open_braces count is less than n:
add open_braces and recurse further
if close_braces count is less than open_braces count:
add close_braces and recurse further
stop recursing when open_braces and close_braces counts are both equal to n
Let’s go through an example , to understand the solution. The output is shown at the leaf level.
Now let’s look at the code in our favorite language below:
Time complexity
As visualized in the slides above, it is easier to understand the problem by creating a tree. Given a tree with branching of ...