当前位置:网站首页>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]));
}
}
}
边栏推荐
- 嵌入式系统驱动初级【2】——内核模块下_参数和依赖
- 零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
- Database Principles Homework 3 — JMU
- Leetcode952. 按公因数计算最大组件大小
- 电脑开机密码怎么设置?如何给你的电脑加上“安全锁”
- 文件 - 07 删除文件: 根据fileIds批量删除文件及文件信息
- 芯塔电子斩获第十一届中国双创大赛芜湖赛区桂冠
- codec2 BlockPool:unreadable libraries
- van-uploader上传图片,使用base64回显无法预览的问题
- Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题
猜你喜欢

One of the small practical projects - food alliance ordering system
解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?

Automatic translation software - batch batch automatic translation software recommendation

360推送-360推送工具-360批量推送工具

tidyverse笔记——dplyr包

什么是半波整流器?半波整流器的使用方法

金融租赁业务

postgresql源码学习(34)—— 事务日志⑩ - 全页写机制

2022.07.20_每日一题

剑指offer(一)
随机推荐
CHI论文阅读(1)EmoGlass: an End-to-End AI-Enabled Wearable Platform for Enhancing Self-Awareness of Emoti
2022.07.12_每日一题
【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
毫米波技术基础
postgresql源码学习(34)—— 事务日志⑩ - 全页写机制
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
codec2 BlockPool:unreadable libraries
线程中断方法
外贸网站优化-外贸网站优化教程-外贸网站优化软件
2022.07.26_每日一题
【TA-霜狼_may-《百人计划》】美术2.3 硬表面基础
庐山谣寄卢侍御虚舟
【并发编程】ReentrantLock的lock()方法源码分析
第9章 异常try...except...else...finally
科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
基金投顾业务
Leetcode952. 按公因数计算最大组件大小
2022.07.13_每日一题
SCI写作指南
04-SDRAM:读操作(突发)