力扣 797. 所有可能路径【DFS】

1. 题目

2. 代码

  • DFS , 直接见代码
cpp 复制代码
class Solution {
public:
    vector<int> path;
    vector<vector<int>> res;    // 结果集
    void dfs(vector<vector<int>>& graph, int cur, int n){
        // 找出所有从节点 0 到节点 n-1 的路径
        // 下标从 0 开始的
        if (cur == n){  // 当前点到了终点
            // 说明找到了一条路径, 收集起来
            res.push_back(path);
            // 返回
            return ;
        }
        // 当前节点下面有什么边连着
        for (const auto& cc : graph[cur]){
            path.push_back(cc); // 收集这个节点
            // 沿着这条路径递归
            dfs(graph, cc, n);
            path.pop_back();    // 回溯
        }
        return ;
    }
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        // dfs
        // 邻接表
        // 从第一个节点出发
        path.push_back(0);
        dfs(graph, 0, graph.size() - 1);
        return res;

    }
};
相关推荐
lisw059 小时前
稀疏算法概述!
算法·机器人·无人机
YLCHUP10 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴11 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu15 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu16 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
凌冰_17 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏18 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
饮水桶_T20 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
饮水桶_T1 天前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥1 天前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm