22. 括号生成
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
#基于搜索的方法(DFS 栈),将括号生成过程想象成一棵树,n表示剩余可用括号数
def generateParenthesis(n):
if n==0:
return []
result = []
cur = ""
stack = [(n,n,cur)]
while stack:
left,right,cur = stack.pop()
if left == right == 0:
result.append(cur)
if left>0 and left-1<=right:
s = "("
stack.append((left-1,right,cur+s))
if right>0 and left<=right-1:
s = ")"
stack.append((left,right-1,cur+s))
return result
#DFS 递归实现
def generateParenthesis(n):
if n==0:
return []
def generate(left,right,cur):
if left == right == 0:
results.append(cur)
return
if left>right:
return
if left>0:
generate(left-1,right,cur+"(")
if right>0:
generate(left,right-1,cur+")")
cur = ""
results = []
generate(n,n,cur)
return results
#动态规划,新的括号基于已有括号扩展
# dp[i] = "(" + dp[j] + ")" + dp[i- j - 1];
def generateParenthesis(n):
if n==0:
return []
dp = [None]*(n+1)
dp[0] = [""]
for i in range(1,n+1):
cur = []
for j in range(i):
left = dp[j] #新括号内部可能的括号数
right = dp[i-j-1] #外部的
for ls in left: #内部可能有j个,对一种可能遍历
for rs in right: #对外部每一种可能遍历
cur.append("("+ls+")"+rs)
dp[i] = cur
print(i,cur)
return dp[n]