题目描述:
题解:参考https://segmentfault.com/a/1190000022110082
1.设计一个递归函数helper(left,right,mystr,res)
left表示剩余左括号数量,right表示剩余右括号数量,mystr表示当前找到的一种组合方式,res保存所有可能结果
left right均为0时说明找到了一种组合,mystr加入res中
left>0,mystr中添加一个左括号,传入新的left值和新的mystr进行递归
right>0,mystr中添加一个右括号,传入新的right和mystr继续递归
2.在generateParenthesis中将left right均设为n,调用helper函数
class Solution(object): def generateParenthesis(self,n): if n==0: return [] res = [] self.helper(n,n,"",res) return res def helper(self,left,right,mystr,res): if left>right: return if left==0 and right==0: res.append(mystr) if left>0: self.helper(left-1,right,mystr+"(",res) if right>0: self.helper(left,right-1,mystr+")",res)
2021.11.11
在学习回溯算法的时候,再次遇到这个题,其实之前的方法也是回溯DFS,搜索过程如下:
用left right分别记录当前剩余可用的左右括号,当right<left可以直接剪枝。