New update is available. Click here to update.
Last Updated: 2 Dec, 2020
##### Generate all parenthesis
Moderate
Problem statement

#### For Example:

``````For βNβ = 3,
All possible combinations are:
((()))
(()())
(())()
()(())
()()()
``````
##### Input Format:
``````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.
``````
Approaches

## 01Approach

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:

1. It will take a number of arguments:
1. βTOTALβ - an integer representing the total number of characters i.e twice the number of pairs.
2. βOPENβ - an integer representing the number of opening brackets till now.
3. βCLOSEβ - an integer representing the number of closing brackets till now.
4. βSβ - a string representing the parenthesis till now.
5. βANSβ - a vector of string to store all the generated parenthesis.
2. If the size of the string becomes equal to βTOTALββ, that means that a valid parenthesis is generated, we will store it in the βANSβ vector.
3. If βOPENβ is greater than βCLOSEβ,
1. then we can give a closing bracket at this index.
2. Again if βOPENβ is less than βTOTALβ / 2, we can also give an opening bracket at this index.
4. Else we can only give an opening bracket at this index.

given function:

1. Declare a variable βTOTALβ with a value twice as βNβ, since each pair consists of two characters.
2. Declare a vector of strings βANSβ to store all the valid parentheses.
3. Call the generate function with zero opening bracket, zero closing bracket, and an empty string.
4. Finally, return the βANSβ vector.