力扣 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;

    }
};
相关推荐
zyl76513 小时前
FlashAttention 详解:从 GPU 硬件、普通 Attention 到分块计算与 Online Softmax
算法
爱读书的小胖17 小时前
LeetCode 122:买卖股票的最佳时机 II(C)解题分析
算法
结局无敌17 小时前
React Native for OpenHarmony 实战:三方库 react-native-modal-dialog 的鸿蒙化适配指南
深度学习·算法·react native·react.js·harmonyos
OPEN-F18 小时前
ROS2系列教程:上位机建图与导航(原理综合)
算法·机器人
weixin_3077791318 小时前
C++代码实现MATLAB中的fitrtree函数功能
开发语言·c++·算法·matlab
tomwang032218 小时前
路径优化建模、优化算法分类及工程化小结
算法·数学建模·分类
小羊没烦恼!18 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
2501_9269783318 小时前
人机通信协议--人和机器之间的交互想象
人工智能·经验分享·算法·ai写作
行者全栈架构师18 小时前
【鸿蒙心迹】互动卡片全链路——把核心功能放到桌面(FormKit 实战)(HarmonyOS 7.x)
前端·算法·架构
无定义_18 小时前
10.11日常训练
算法