Leetcode 22. Generate Parentheses

来源:互联网 发布:林志炫浮夸知乎 编辑:程序博客网 时间:2024/06/05 02:19

题目:

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:

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

思路:

用一个标志变量stackNum模拟一个栈中'('的数量,递归生成所需要的序列,若栈空则入左括号,若栈不空则有两种可能分别递归执行,直到左右括号皆用完。


class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        if n<=0:return []
        res = []
        self.generator(n,n,0,'',res)
        return res
        
        
    def generator(self,n_l,n_r,stackNum,curStr,res):
        if n_l<=0 and n_r<=0:
            res.append(curStr)
            return
        if stackNum==0:
            self.generator(n_l-1,n_r,stackNum+1,curStr+'(',res)
        else:
            if n_l>0:
                self.generator(n_l-1,n_r,stackNum+1,curStr+'(',res)
            if n_r>0:
                self.generator(n_l,n_r-1,stackNum-1,curStr+')',res)
            


0 0