您的位置:首页 > 其它

Leetcode 22. Generate Parentheses

2017-04-24 15:22 267 查看
题目:

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)

            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode