Given N pairs of parentheses, write a function to generate and print all combinations of well-formed parentheses. That is, you need to generate all possible valid sets of parentheses that can be formed with a given number of pairs.
The only line of input contains an integer ‘N’ representing the given number of parentheses.
Output Format:
The output contains all possible valid parentheses printed in different lines.
Note:
The order in which different combinations of well-formed parentheses are printed doesn't matter.
1 <= N <= 10
Time Limit: 1sec
3
{{{}}}
{{}{}}
{{}}{}
{}{{}}
{}{}{}
These are the only five sequences of balanced parentheses formed using 3 pairs of balanced parentheses.
2
{{}}
{}{}
Use recursion to print each valid sequence of brackets.
To form all the sequences of balanced bracket subsequences with N pairs. So there are N opening brackets and N closing brackets.
So the subsequence will be of length 2 * N. There is a simple idea, the i’th character can be ‘{‘ if and only if the count of ‘{‘ till i’th is less than N and i’th character can be ‘}’ if and only if the count of ‘{‘ is greater than the count of ‘}’ till index i. If these two cases are followed then the resulting subsequence will always be balanced. So form the recursive function using the above two cases.
Below is the algorithm:
O(2 ^ N), where ‘N’ is the given number.
Since, for every index there can be two options ‘{‘ or ‘}’. So it can be said that the upper bound of time complexity is O(2 ^ N) or it has exponential time complexity.
O(N), where ‘N’ is the given number.
We are using O(H) extra space for the call stack where ‘H’ is the height of the recursion stack, and height of a recursion stack could be N in the worst case. Thus, the final space complexity is O(N).