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

Question

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: ["()"]

Constraints:

  • 1 <= n <= 8

Python Solution

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n==0:
            return []
         
        return self.rec(n,'',0,0,[])

    def rec(self,n,s,opened,closed,result):
        
        if opened==n and closed!=n:
            result.append((s + ')'*(n-closed)))

        elif opened==closed and opened<=n:
            self.rec(n,s+'(',opened+1,closed,result)

        elif opened > closed and opened<=n:
            self.rec(n,s+')',opened,closed+1,result)
            if opened<n:
                self.rec(n,s+'(',opened+1,closed,result)

        return result
Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *