给出n代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
import itertools
import numpy as np
class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
datas = []
result_true = []
i = n
while i!=1:
datas.append(2*(i-1))
datas.append(2*(i-1)-1)
i-=1
result = list(itertools.combinations(datas, n-1))
print(result)
lenght = result.__len__()-1
while lenght!=-1:
datas_child = np.ones(2*(n),dtype=int)
datas_child[2*(n)-1]=-1
lenght_child = result[lenght].__len__()-1
while lenght_child!=-1:
child_index = result[lenght][lenght_child]
datas_child[child_index] = -1
lenght_child -= 1
result_lenght = datas_child.__len__()
i=0
result_child = 0
ok = True
while i<result_lenght:
result_child+=datas_child[i]
if result_child<0:
result.pop(lenght)
ok = False
break
i+=1
if ok:
c = datas_child.astype('str')
c[datas_child == 1] = '('
c[datas_child == -1] = ')'
result_true.append(''.join(c))
lenght-=1
return result_true
作者:不爱去冒险的少年y
链接:https://www.jianshu.com/p/20a5e164e366