2021-08-25 力扣刷题笔记
前言
今天出了趟门,十一点才到家,又累又困,只做了一道每日一题,还是抄的三宫姐姐的代码,555明天一定好好刷题
每日一题 797. 所有可能的路径
题目描述
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。
译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。
示例 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]]
示例 3:
输入:graph = [[1],[]]
输出:[[0,1]]
示例 4:
输入:graph = [[1,2,3],[2],[3],[]]
输出:[[0,1,2,3],[0,2,3],[0,3]]
示例 5:
输入:graph = [[1,3],[2],[3],[]]
输出:[[0,1,2,3],[0,3]]
解题思路
使用DFS进行搜索,起始将0加入到答案中,当n - 1被放入答案时,说明找到了一条从 0 到 n - 1 的通路,将此答案放入结果集中。
代码实现
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
cur.add(0);
dfs(graph, ans, cur, 0);
return ans;
}
void dfs(int[][] graph, List<Integer>> ans, List<Integer> cur, int u){
if(u == graph.length - 1){
ans.add(new ArrayList<>(cur));
return ;
}
for(int next : graph[u]){
cur.add(next);
dfs(graph, ans, cur, next);
cur.remove(cur.size() - 1);
}
}
}

浙公网安备 33010602011771号