再會。我有一個關于何時在遞回中使用 return 的問題。我基本上想使用遞回來解決以下問題:
給定一個二叉樹的根和一個整數 targetSum,回傳所有根到葉的路徑,其中路徑中節點值的總和等于 targetSum。每個路徑都應該作為節點值的串列回傳,而不是節點參考。根到葉路徑是從根開始到任何葉節點結束的路徑。葉節點是沒有子節點的節點。
輸入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
輸出:[[5,4,11,2],[5,8,4,5]]
說明:有兩條路徑的總和等于 targetSum:
5 4 11 2 = 22
5 8 4 5 = 22
這是我的代碼解決方案
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res = []
def helper(node, target, cur):
if not node:
return
cur.append(node.val)
if target == node.val and not node.left and not node.right:
res.append(list(cur))
print(res)
return # why can't we put return here
helper(node.left, target - node.val, cur)
helper(node.right, target- node.val, cur)
cur.pop()
helper(root, targetSum, [])
return res
我想當我們找到一個解決方案時,我們可以停止并回傳 res。但它會給我一個奇怪的輸出。有人能教我為什么我們不能把退貨放在這里。任何建議,將不勝感激。
uj5u.com熱心網友回復:
此代碼使用回溯方法來查找問題的所有解決方案(路徑)。
當您提前回傳時,您就剝奪了pop添加到當前串列的最后一個元素的解決方案的機會。洗掉早期回傳并讓演算法處理在基本情況下的回傳,回傳遞回堆疊和pop當前路徑中的最后一個元素,如下所示:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
res = []
def helper(node, target, cur):
if not node:
return
cur.append(node.val)
if target == node.val and not node.left and not node.right:
res.append(list(cur))
print(res)
# when your code comes out of this if condition
# node.left and node.right will be None
# it calls the below functions and they return
# and then it will pop the last element
helper(node.left, target - node.val, cur)
helper(node.right, target- node.val, cur)
cur.pop()
helper(root, targetSum, [])
return res
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376313.html
下一篇:奇數/偶數遞回函式中的分段錯誤
