题目思路:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
#思路:定义一个括号生成的递归函数,第一个参数为有效的括号组合,第二个参数为当前的括号字符串,第三个参数为括号的对数,第四个参数为当前括号字符串中左括号的个数,第五个参数为当前括号字符串中右括号的个数
res = []
temp = '('
l_num = 1
r_num = 0
if n == 0:
return res
def generate(list_,ss,nums,l_nums,r_nums):
if nums == l_nums and nums == r_nums:
list_.append(ss)
elif nums == l_nums and nums != r_nums:
ss = ss + (nums-r_nums)*')'
list_.append(ss)
else:
if l_nums == r_nums:
ss = ss + '('
generate(list_,ss,nums,l_nums+1,r_nums)
else:
tt = ss + '('
generate(list_,tt,nums,l_nums+1,r_nums)
tt = ss + ')'
generate(list_,tt,nums,l_nums,r_nums+1)
generate(res,temp,n,l_num,r_num)
return res
菜鸟一枚,代码仅供参考,如有问题,望指正~