Generate parenthesis

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

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

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        parenthesisList = []
        self.generateParenthesisHelper("", parenthesisList, 0, 0, n)
        return parenthesisList

    def generateParenthesisHelper(self, subList, parenthesisList, open, close, max):
        if len(subList) == 2 * max:
            parenthesisList += [subList]
            #print '        *** subList: ', subList, ' ***'
            return

        if open < max:
            #print 'open = ', open, 'max = ', max
            self.generateParenthesisHelper(subList + "(", parenthesisList, open + 1, close, max)
            #print '  > return from ( < '

        if close < open:
            #print 'close = ', close, 'open = ', open
            self.generateParenthesisHelper(subList + ")", parenthesisList, open, close + 1, max)
            #print '  > return from ) < '

Last updated

Was this helpful?