回溯:选择(展开树),约束(剪枝),目标(结束回溯)
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
le, ri = 0, 0
res = []
def tra(n, le, ri, tmp):
if n==le and n==ri:
res.append(tmp)
return
if ri<le and le<n:
newtmp = tmp
tra(n,le+1,ri,newtmp+'(')
tra(n,le,ri+1,newtmp+')')
elif ri==le and le<n:
newtmp = tmp
tra(n,le+1,ri,newtmp+'(')
elif le==n and ri<le:
newtmp = tmp
tra(n,le,ri+1,newtmp+')')
return
tra(n,le,ri,'')
return res
还是回溯
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits=='':return []
dic = {'2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'],
'6':['m','n','o'], '7':['p','q','r','s'], '8':['t','u','v'], '9':['w','x','y','z']}
cur = 0
res=[]
def tra(cur,tmp,digits):
if cur==len(digits):
res.append(tmp)
return
if cur<=len(digits):
newtmp = tmp
for item in dic[digits[cur]]:
tra(cur+1,newtmp+item,digits)
return
tra(cur,'',digits)
return res
直径的两端一定分居在某一个节点的两侧,计算每个节点的左右深度即可。
后序遍历,对每个节点维护左深度、右深度、深度、直径四个变量。
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
if not root:return 0
dic={}
maxdep=[]
def tra (root):
if root.left:
tra(root.left)
dic[(root,1)]=dic[root.left]+1
else:dic[(root,1)]=0
if root.right:
tra(root.right)
dic[(root,2)]=dic[root.right]+1
else:dic[(root,2)]=0
dic[root]=max(dic[(root,1)],dic[(root,2)])
maxdep.append(dic[(root,1)]+dic[(root,2)])
tra(root)
return(max(maxdep))