如何解决Path Sum的递归实施问题
我正在尝试通过leetcode(#113 Path Sums II)来解决这个问题。
给出一个二叉树和一个和,找到所有从根到叶的路径,其中每个路径的和等于给定的目标和。
我的方法:
这个问题似乎已经可以递归了。我从树的顶端开始。每次遇到非叶子节点时,我都会进一步递归到树中,同时跟踪我拍摄的current_path
和我的current_sum
。如果确实遇到叶节点,则检查我的current_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_path)
dfs(root,[])
return paths
但是,由于某种原因,我的current_path变量的作用类似于全局变量...在我的脑海中,每次调用dfs()
时,我们都会创建一个单独的current_path
变量,该变量将传递给{{ 1}}函数,我们稍后再调用。但是,当我实际运行代码dfs()
时,会跟踪我访问过的所有节点。
极其奇怪的是,即使current_path
跟踪其他递归调用中发生的情况,但current_path
却没有。但是我在其他递归实现中从未遇到过这个问题...
任何指针将不胜感激:)
解决方法
我的猜测是您要在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,res)
res = []
if not root:
return res
depth_first_search(root,[],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,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,paths);
depthFirstSearch(node->right,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,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,res);
pathSum(node.right,res);
}
tempRes.remove(tempRes.size() - 1);
}
}
参考文献
- 有关其他详细信息,请参见Discussion Board,在这里您可以找到许多具有各种languages且已被广泛接受的解决方案,包括低复杂度算法和渐近runtime / {{ 3}}分析memory,1 。
考虑使用Python强大的生成器解决问题-
# first:you could find the sum of count groupby date
df_ = df.groupby(by='Date')['Count'].sum()
date_2_count = df_.to_dict()
# then: you could calculate the %change by date_2_count
df['%Change'] = df.apply(lambda x: x['Count']*100/date_2_count[x['Date']],axis=1)
def pathSum(root: TreeNode,target: int): -> List[List[int]]
def dfs(node,path = []):
if not node:
yield path
else:
yield from dfs(node.left,[*path,node.val])
yield from dfs(node.right,node.val])
def filter():
for path in dfs(root):
if sum(path) == target:
yield path
return list(filter())
和dfs
的关注点分开使得该程序易于编写。生成器为我们提供了线性的 O(n)性能。
现在我们知道生成器了,该程序的更自然的版本可能是-
filter
更好的是,由于我们不再返回def pathSum(root: TreeNode,path = []):
# ...
def filter():
# ...
yield from filter() # <- generator
,因此我们可以直接编写list
循环-
for
您可以使用def pathSum(root: TreeNode,target: int):
def dfs(node,node.val])
for path in dfs(root):
if sum(path) == target:
yield path # <- pathSum can yield too!
-
for
或在for answer in pathSum(root,target):
print("solution found:",answer)
# ...
中收集所有答案-
list
您是否注意到我们可以将内存使用量减少一半?因为answers = list(pathSum(root,target))
print(answers)
# [ ... ]
没有突变,所以每个path
子进程可以共享一个内存引用-
dfs
希望您能从Python生成器中学到一些有趣的东西!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。