当前位置:网站首页>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]));
}
}
}
边栏推荐
- Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
- 强化学习科研知识必备(数据库、期刊、会议、牛人)
- LeetCode刷题——摆动序列#376#Medium
- iOS大厂面试查漏补缺
- 快速傅里叶变换(FFT)
- 简单谈谈Feign
- What is float?What is document flow?Several ways and principles of clearing floats?What is BFC, how to trigger BFC, the role of BFC
- Moment.js common methods
- Markdown中的数学符号
- tidyverse笔记——tidyr包
猜你喜欢
HighTec 的安装与配置
LeetCode brush # 376 # Medium - swing sequence
文件 - 05 下载文件:根据文件Id下载文件
【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
高并发与多线程之间的难点对比(容易混淆)
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
Analysis of the implementation principle and detailed knowledge of v-model syntactic sugar and how to make the components you develop support v-model
【编程题】【Scratch三级】2022.03 冬天下雪了
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
MySql的安装配置超详细教程与简单的建库建表方法
随机推荐
mysql索引失效的常见9种原因详解
opencv、pil和from torchvision.transforms的Resize, Compose, ToTensor, Normalize等差别
2022.7.29 数组
Leetcode952. 按公因数计算最大组件大小
双倍数据速率同步动态随机存储器(Double Data Rate Synchronous Dynamic Random Access Memory, DDR SDRAM)- 逻辑描述部分
MySQL的触发器
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
【云原生】-Docker容器迁移Oracle到MySQL
【Star项目】小帽飞机大战(八)
熟悉而陌生的新朋友——IAsyncDisposable
一文读懂 MongoDB 和 MySQL 的差异
知识、创新、回报。
Database Principles Homework 2 — JMU
PCB抄板
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
【第四章】详解Feign的实现原理
Chapter 16: Constructing the Magic Square for Prime Numbers of Order n(5,7)
拓扑排序的两种方法 --- dfs+Kahn
codec2 BlockPool:不可读库
Database Principles Homework 3 — JMU