给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result=[]
self.add(0,0,result,True,n,"")
return result
def add(self,count,pcount,result,lr,n,string):
#count=无配对的左括号数,pcount=已经配对数,lr=加左括号还是右括号
if lr:#left
count+=1
string+='('
if (count+pcount)>n:
return
else:
if count==0:
return
else:
count-=1
pcount+=1
string+=')'
if pcount==n:
result.append(string)
return
self.add(count,pcount,result,True,n,string)
self.add(count,pcount,result,False,n,string)