当前位置:网站首页>2022.07.14_Daily Question
2022.07.14_Daily Question
2022-07-31 07:39:00 【No. い】
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]]
提示:
n == graph.length2 <= n <= 150 <= graph[i][j] < ngraph[i][j] != i(即不存在自环)graph[i]中的所有元素 互不相同- 保证输入为 有向无环图(DAG)
- 深度优先搜索
- 广度优先搜索
- 图
- 回溯
coding
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<>();
int index = 0;
List<Integer> record = new ArrayList<>();
// 从 0 出发
record.add(0);
dfs(graph, res, index, record);
return res;
}
private void dfs(int[][] graph, List<List<Integer>> res, int index, List<Integer> record) {
// 到 n - 1 over
if (index == graph.length - 1) {
// The current record is added to the path of res
res.add(new ArrayList<>(record));
return;
}
for (int i = 0; i < graph[index].length; i++) {
// Add a pointer to the node under
record.add(graph[index][i]);
// Add the current node as the index of the next node location, Starting from the next node to continue dfs
dfs(graph, res, graph[index][i], record);
// 回溯
// 【PS】: list.remove(int 索引)
// list.remove(new Integer(list 集合中的元素))
record.remove(new Integer(graph[index][i]));
}
}
}
边栏推荐
- 2022.07.20_每日一题
- LeetCode brush # 376 # Medium - swing sequence
- 英语翻译软件-批量自动免费翻译软件支持三方接口翻译
- 【Go】Go 语言切片(Slice)
- 2022.07.14_每日一题
- gstreamer的caps event和new_segment event
- Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software
- 2022.07.12_每日一题
- Financial leasing business
- 基于LSTM的诗词生成
猜你喜欢
随机推荐
【面试:并发篇38:多线程:线程池】ThreadPoolExecutor类的基本概念
事务的传播机制
Database Principles Homework 3 — JMU
Third-party library-store
opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题
leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
04-SDRAM: Read Operation (Burst)
codec2 BlockPool:不可读库
Kubernetes调度
DirectExchange交换机简单入门demo
Leetcode952. 按公因数计算最大组件大小
SQL Server Datetime2数据类型
Moment.js common methods
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
服务器和客户端信息的获取
【Go语言刷题篇】Go完结篇函数、结构体、接口、错误入门学习
链表实现及任务调度
How to choose a suitable UI component library in uni-app
什么是半波整流器?半波整流器的使用方法









