797. 所有可能的路径(图的遍历)
难度中等
给你一个有 n
个节点的 有向无环图(DAG),请你找出所有从节点 0
到节点 n-1
的路径并输出(不要求按特定顺序)
graph[i]
是一个从节点 i
可以访问的所有节点的列表(即从节点 i
到节点 graph[i][j]
存在一条有向边)。
示例 1:
输入:graph = [[1,2],[3],[3],[]] 输出:[[0,1,3],[0,2,3]] 解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例 2:
输入:graph = [[4,3,1],[3,2,4],[3],[4],[]] 输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
class Solution: def __init__(self) -> None: self.res = [] def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: def dfs(path,graph,node): if node >= len(graph)-1: path.append(node) self.res.append(path.copy()) path.pop() return for children in graph[node]: path.append(node) dfs(path,graph,children) path.pop() path = [] dfs(path,graph,0) return self.res
class Solution { public: vector<vector<int>> res; void dfs(vector<int>& path, vector<vector<int>>& graph, int cur_node) { path.emplace_back(cur_node); if (graph.size()-1 == cur_node) { res.emplace_back(path); // 可以在这直接 return,但要 pop_back 正确维护 path // path.pop_back(); // return; // 不 return 也可以,因为图中不包含环,不会出现无限递归 } for(auto nenbor: graph[cur_node]) { dfs(path,graph,nenbor); } path.pop_back(); } vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<int> path; dfs(path,graph,0); return res; } };
分类:
LeetCode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-05-16 将Pytorch模型从CPU转换成GPU
2018-05-16 tensorflow显存管理
2018-05-16 搭建Python3的jupyter notebook服务器
2017-05-16 ubuntu16.04(liunx) 离线安装 xgboost (anaconda3,anaconda2共存)