【问题标题】:When should we add return in the recursion我们什么时候应该在递归中添加 return
【发布时间】:2022-01-13 03:19:23
【问题描述】:

美好的一天。我可以问一个关于何时在递归中使用 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

我想当我们找到一个解决方案时,我们可以停止并返回资源。 但它会给我一个奇怪的输出。有人可以教我为什么我们不能把 return 放在这里。任何建议将不胜感激。

【问题讨论】:

  • 您能否用一张图来编辑您的问题,以说明[5,4,8,11,null,13,4,7,2,null,null,5,1] 代表的是什么树?
  • 没问题!完成

标签: python algorithm recursion


【解决方案1】:

此代码使用回溯法来查找问题的所有解决方案(路径)。

当您提前返回时,您剥夺了解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 2020-09-14
    • 2021-09-07
    相关资源
    最近更新 更多