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

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 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.