algorithm - Path Sum 的递归实现问题
问题描述
我正在尝试从 leetcode(#113 Path Sums II) 中回答这个问题。
给定一棵二叉树和一个总和,找到所有从根到叶的路径,其中每个路径的总和等于给定的目标总和。
我的做法:
这个问题似乎适合递归。我从树的最顶端开始。每次遇到非叶节点时,我都会进一步递归到树中,同时跟踪current_path
我采取的和我的current_sum
. 如果我遇到叶节点,我会检查 mycurrent_sum
是否等于target
. 如果是,我将该路径添加到我想要返回的路径列表中。否则,我们会探索其他路径。
def pathSum(self, root: TreeNode, target: int) -> List[List[int]]:
paths = [] #variable we return
def dfs(node, current_sum = 0, current_path = []):
if not node:
return False #Edge case
# Adding my current place
current_path.append(node.val)
current_sum += node.val
if not node.left and not node.right: # Is this a leaf node?
if current_sum == target: #Is the sum == target
paths.append(current_path) #Add the current path
else: #keep recursing since we are not at the leaf
dfs(node.left, current_sum, current_path)
dfs(node.right, current_sum, current_path)
dfs(root,0,[])
return paths
但是,由于某种原因,我的 current_path 变量就像一个全局变量......在我的脑海中,每次dfs()
调用我们都会创建一个单独的current_path
变量,该变量会传递给dfs()
我们稍后调用的函数。但是,当我实际运行代码时,current_path
会跟踪我访问过的所有节点。
极其奇怪的是,即使current_path
跟踪其他递归调用中发生的事情,current_sum
也不会。我从来没有遇到过其他递归实现的这个问题......
任何指针将不胜感激:)
解决方案
我的猜测是,您在没有任何条件语句的情况下node.val
在此处附加了任何内容:current_path
current_path.append(node.val)
这可能会导致算法错误。
在 Python 中,这将通过,与 DFS 类似:
class Solution:
def pathSum(self, root, target):
def depth_first_search(node, target, path, res):
if not (node.left or node.right) and target == node.val:
path.append(node.val)
res.append(path)
if node.left:
depth_first_search(node.left, target - node.val, path + [node.val], res)
if node.right:
depth_first_search(node.right, target - node.val, path + [node.val], res)
res = []
if not root:
return res
depth_first_search(root, target, [], res)
return res
同样在 C++ 中:
// The following block might trivially improve the exec time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return 0;
}();
#include <vector>
const static struct Solution {
const static std::vector<std::vector<int>> pathSum(
const TreeNode* root,
const int sum
) {
std::vector<std::vector<int>> paths;
std::vector<int> path;
depthFirstSearch(root, sum, path, paths);
return paths;
}
private:
const static void depthFirstSearch(
const TreeNode* node,
const int sum,
std::vector<int>& path,
std::vector<std::vector<int>>& paths
) {
if (!node) {
return;
}
path.emplace_back(node->val);
if (!node->left && !node->right && sum == node->val) {
paths.emplace_back(path);
}
depthFirstSearch(node->left, sum - node->val, path, paths);
depthFirstSearch(node->right, sum - node->val, path, paths);
path.pop_back();
}
};
在 Java 中,我们会使用两个 LinkedList:
public final class Solution {
public static final List<List<Integer>> pathSum(
final TreeNode root,
final int sum
) {
List<List<Integer>> res = new LinkedList<>();
List<Integer> tempRes = new LinkedList<>();
pathSum(root, sum, tempRes, res);
return res;
}
private static final void pathSum(
final TreeNode node,
final int sum,
final List<Integer> tempRes,
final List<List<Integer>> res
) {
if (node == null)
return;
tempRes.add(new Integer(node.val));
if (node.left == null && node.right == null && sum == node.val) {
res.add(new LinkedList(tempRes));
tempRes.remove(tempRes.size() - 1);
return;
} else {
pathSum(node.left, sum - node.val, tempRes, res);
pathSum(node.right, sum - node.val, tempRes, res);
}
tempRes.remove(tempRes.size() - 1);
}
}
参考
推荐阅读
- php - 我的 php codeigniter 项目不能在 linux 中运行,但可以在 windows 中运行
- javascript - 如何防止电子中弹出多个通知?
- android-studio - 在 Windows 上的 Android Studio 中调试 Intellij Idea 插件
- python - `conda` 给出“没有这样的文件或目录”,尽管我在 .bash_profile 中添加了 PATH
- typescript - 类实例在 TypeScript 中返回空白对象
- firebase - 即使用户在 facebook 登录过程中拒绝它,我也有兴趣获取用户的电子邮件地址
- javascript - 将数组中的元素从某个索引移动到 0
- javascript - 图像过滤器插件在一个项目中有效,但在另一个项目中无效
- flutter - 用于下载种子的 Flutter 插件
- python - 包含多个元素的 Zip 列表