• Customer Support: admin@thealgorists.com
  • Feedback: We are listening to your every feedback, and taking action to constantly improve your learning experience. If you have any feedback, please use this form: https://thealgorists.com/Feedback.



Problem Statement:


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:
Input: n = 1
Output: ["()"]

Solution:


  • NOTE: I highly recommend going through the Backtracking chapters in the order they are given in the Index page to get the most out of it and be able to build a rock-solid understanding.


If you are familiar with our backtracking template then you would be easily come up with a quick solution for this problem just by making the below two observations:

We need to ask ourselves two questions:
  • When can we add an opening brace "(" to a given empty or non-empty partial solution ?
  • When can we add a closing brace ")" to a given empty or non-empty partial solution ?
When we have n = 3 (you can take whatever n you want) below are all the configurations we can get: "((()))", "(()())", "(())()", "()(())", "()()()"

Looking at the patterns carefully, we can conclude:
  1. We always have room for appending one more opening brace "(" to a given partial solution as long as partial solution contains less than n opening braces.

    "(" can be added to an empty partial solution.

    Keep in mind we cannot have more than n opening braces in our solution.

  2. We can append closing brace ")" to our partial solution only when we have less number of closing braces than opening braces in our current partial solution.

    ")" cannot be added to an empty partial solution.

This leads to the below code. I have put additional logic in the inline comment for your better understanding.

Java Code:



This is a Premium content.
Please subscribe to Algorithms course to access the code.




Python Code:



This is a Premium content.
Please subscribe to Algorithms course to access the code.





Time Complexity:




Please subscribe to access the complexity analysis.




Don't forget to take in-depth look at the other backtracking problems because that is what would make you comfortable with using the backtracking template and master the art of Backtracking:


The above content is written by:

Abhishek Dey

Abhishek Dey

A Visionary Software Engineer With A Mission To Empower Every Person & Every Organization On The Planet To Achieve More

Microsoft | University of Florida

View LinkedIn profile


If you have any feedback, please use this form: https://thealgorists.com/Feedback.




Subscribe to Our Youtube Channel

Follow Us On LinkedIn
wave