Path Sum的递归实施问题

如何解决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}}分析memory1
,

考虑使用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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-