Problem of the day
You are given an integer 'N', your task is to generate all combinations of well-formed parenthesis having ‘N’ pairs.
A parenthesis is called well-formed if it is balanced i.e. each left parenthesis has a matching right parenthesis and the matched pairs are well nested.
For Example:
For ‘N’ = 3,
All possible combinations are:
((()))
(()())
(())()
()(())
()()()
Input consists of a single line containing a single integer ‘N’, representing the number of pairs in the parentheses.
Output Format:
Print list of strings denoting all possible combinations for the given integer in a lexicographically ascending order.
Note
You are not required to print anything, it has already been taken care of. Just implement the function.
2
()()
(())
There are two possible combinations of parentheses:
()()
(())
Here both the parenthesis are balanced so the possible outputs can be [ [ ()() ],[ (()) ] ].
4
()()()()
()()(())
()(())()
()(()())
()((()))
(())()()
(())(())
(()())()
(()()())
(()(()))
((()))()
((())())
((()()))
(((())))
1 <= 'N' <= 11
Time Limit: 1 sec.
Try to fix both the opening and closing bracket at each index if possible.
We will try to fix both the opening and closing brackets at each index if it can lead to a valid parenthesis. For a parenthesis to be valid, at each index the number of the opening bracket in the prefix of that index should be greater than or equal to the number of closing brackets.
Algorithm:
generate function:
given function:
O(2 ^ N), where ‘N’ is the total number of characters.
Since at each index, we have two possibilities(opening and closing brackets) the total time complexity will be O(2 ^ N).
O(1),
Constant extra space is used.