数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
有效括号组合需满足:左括号必须以正确的顺序闭合。
例:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = {''} # 结果
for i in range(n): # n为几则循环几次
temp = set() # 设置用set()函数进行去重
for s in result: # 结果里面的对象
for j in range(len(s) + 1): # 可以插入'()'的位置
temp.add(s[:j] + '()' + s[j:]) # 选择插入'()'的位置
result = temp # 将值传给result进行下一轮计算
return list(result) # 转换成列表对象