Generate Parentheses

Question

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

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Tags

  • Backtracking
  • String

Thought

Use the backtracking here.

Code

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        result = []

        def helper(current, left, right):
            if right == n:
                result.append(current)
                return
            if left < n:
                helper(current + '(', left + 1, right)
            if right < left:
                helper(current + ')', left, right + 1)

        helper('', 0, 0)
        return result

results matching ""

    No results matching ""