006-力扣刷题22--括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

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

image.png **不能出现这种的情况 )( **

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        if n == 0:  #如果n是零的话那么就返回一个空的列表,没什么好说的
            return []

        result = []  #在n不等于零的时候进行递归遍历

        self.helper(n,n,'',result)

        return result  #返回最终的结果
    def helper (self , l,r,item,result): #l是左括号的个数,r是右括号的个数,item存储的每一个符合要求的字符串((()))类似这种的
        if r < l :   #这个是去除错误的字符串的判断的 当r<l 也就是说剩下的(的个数比)括号的个数少也就是这种情况 ()) 实际上应该左括号要么比右括号用的多,剩下的就少才能满足要求  .这个判断语句就筛除了所有不满足添加的字符串
            return
        if l == 0 and r == 0:
            result.append(item) #当左右括号都用完的使用我们将这个item添加到result中
            #一开始先添加左括号也是一个必要的条件
        if l > 0:   #当左括号还剩下的时候那么就让左括号的数量减1右括号的数量不变,item串加上一个左括号,然后就是递归
            self.helper(l-1,r,item+'(',result)
        if r >0: #有括号的添加也是一样的
            self.helper(l,r-1,item+')',result)