我们的规则是 在一个未完成的序列中
"(“的个数一定要大于等于”)"的个数
且“(”的个数要小于等于n
当“(”的个数小于n时
若 "(“的个数大于”)“的个数
可以都填
若”(“的个数等于”)"的个数
只能填)
当“(”的个数小==n时
只能填)
当序列长度 = 2n时 记录结果
class Solution:
def __init__(self):
self.res = []
self.hashdict = {}
self.length = 0
def generateParenthesis(self, n: int) -> List[str]:
#res = []
self.length = n * 2
self.qpl('(',1,0)
return self.res
def qpl(self,lastres,front,back):
if len(lastres) == self.length:
if lastres not in self.hashdict:
self.hashdict[lastres] = 1
self.res.append(lastres)
elif len(lastres) <self.length:
if front == back:
self.qpl(lastres + '(',front + 1,back)
elif front > back:
if 2*front < self.length:
self.qpl(lastres + '(', front + 1, back)
self.qpl(lastres + ')', front, back + 1)
elif 2*front == self.length:
self.qpl(lastres + ')', front, back + 1)