DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

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)