This post is completed by 2 users

  • 1
Add to List
Medium

116. Generate All Balanced Parentheses Combinations (N Pairs)

Objec­tive: - Given "n", generate all valid parenthesis strings of length "2n".
Example:

Given n=2

Output:
(())
()()

Approach:

  1. Recursion is the key here.
  2. Divide the N into N/2 and N/2 (Count for open and closed parentheses ).
  3. Select the open parentheses, add it to the result string and reduce its count and make a recursive call.
  4. Select the close parentheses, add it to the result string and reduce its count and make a recursive call.
  5. To print only valid parentheses, make sure at any given point of time, close parentheses count is not less that open parentheses count because it means close parentheses has been printed with its respective open parentheses.
  6. See picture for better explanation.
Generate all valid parenthesis strings of length 2n of given n
 

Output:

(())
()()