当前位置:网站首页>2022.07.14_每日一题
2022.07.14_每日一题
2022-07-31 06:07:00 【诺.い】
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.length
2 <= n <= 15
0 <= graph[i][j] < n
graph[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) {
// 将当前记录的路径添加至 res
res.add(new ArrayList<>(record));
return;
}
for (int i = 0; i < graph[index].length; i++) {
// 添加下一个指针指向节点
record.add(graph[index][i]);
// 把当前添加的节点当作下一节点的索引位置, 从下一节点开始继续 dfs
dfs(graph, res, graph[index][i], record);
// 回溯
// 【PS】: list.remove(int 索引)
// list.remove(new Integer(list 集合中的元素))
record.remove(new Integer(graph[index][i]));
}
}
}
边栏推荐
- 文件 - 04 下载文件: 根据文件下载链接下载文件
- 4-1-7 二叉树及其遍历 家谱处理 (30 分)
- 03-SDRAM:写操作(突发)
- SCI写作指南
- 【微服务】(十六)—— 分布式事务Seata
- 从 Google 离职,前Go 语言负责人跳槽小公司
- 强化学习科研知识必备(数据库、期刊、会议、牛人)
- 解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie
- 【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
- 我开发了一个利用 Bun 执行 .ts / .js 文件的 VS Code 插件
猜你喜欢
拓扑排序的两种方法 --- dfs+Kahn
文件 - 04 下载文件: 根据文件下载链接下载文件
【网络攻防】常见的网络攻防技术——黑客攻防(通俗易懂版)
把 VS Code 当游戏机
从 Google 离职,前Go 语言负责人跳槽小公司
Run the NPM will pop up to ask "how are you going to open this file?"
一文读懂 MongoDB 和 MySQL 的差异
One of the small practical projects - food alliance ordering system
Core Tower Electronics won the championship in the Wuhu Division of the 11th China Innovation and Entrepreneurship Competition
双倍数据速率同步动态随机存储器(Double Data Rate Synchronous Dynamic Random Access Memory, DDR SDRAM)- 逻辑描述部分
随机推荐
【Star项目】小帽飞机大战(七)
【Star项目】小帽飞机大战(八)
tidyverse笔记——dplyr包
Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
【云原生】-Docker容器迁移Oracle到MySQL
PCB抄板
QFileInfo常规方法
Chapter 17: go back to find the entrance to the specified traverse, "ma bu" or horse stance just look greedy, no back to search traversal, "ma bu" or horse stance just look recursive search NXM board
Some derivation formulas for machine learning backpropagation
postgresql源码学习(34)—— 事务日志⑩ - 全页写机制
【Go语言刷题篇】Go完结篇函数、结构体、接口、错误入门学习
nohup principle
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
Gradle remove dependency demo
快速傅里叶变换(FFT)
剑指offer(一)
【微服务】Nacos集群搭建以及加载文件配置
03-SDRAM: Write operation (burst)
Jobject 使用
Postgresql source code learning (34) - transaction log ⑩ - full page write mechanism