# 22. Generate Parentheses Leetcode Solution

## Generate Parentheses Leetcode Problem :

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

## Generate Parentheses Leetcode Solution :

• 1 <= n <= 8

### Example 1:

• Input: n = 1
• Output: [“()”]

Intuition :

This problem is one of the classical recursion problems.
For any given n, lets say n = 2, we have to fill four places in our output (“_ _ _ _”). And each of these places can be either filled by an open braces “(” or a closed braces “)”.

Approach :

• Whenever we have count of open brackets equal to the count of close brackets, we have only one choice – that is to use ‘(‘. Because, all the brackets till now have been balanced. And we can not start a new sequence with ‘)’.
• Whenever, count of close bracket is 0, we can only use ‘(‘.
• Whenever, count of open bracket is 0, we can only use ‘)’.
• And for all the remaining cases, we have both the choices.
• We get an answer, when count of open == 0 and count of close == 0.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others