DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1

Generate Parentheses

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

SOLUTION:

class Solution:
    def generate(self, s, ctr, rem, ans):
        if rem == 0 and ctr == 0:
            ans.add(s)
        if rem > 0 and ctr >= 0:
            if ctr < rem:
                self.generate(s + '(', ctr + 1, rem - 1, ans)
            if ctr > 0:
                self.generate(s + ')', ctr - 1, rem - 1, ans)

    def generateParenthesis(self, n: int) -> List[str]:
        ans = set()
        self.generate("", 0, 2 * n, ans)
        return list(ans)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay