我又重新开始更新LeetCode了,以后工作日更新LeetCode,周末更新东野圭吾的小说
这题是LeetCode第797题,中等难度。
原题地址:https://leetcode-cn.com/problems/all-paths-from-source-to-target/
题目描述:
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。
示例:
输入: [[1,2], [3], [3], []]
输出: [[0,1,3],[0,2,3]]
解释: 图是这样的:
0--->1
| |
v v
2--->3
这有两条路: 0 -> 1 -> 3 和 0 -> 2 -> 3.
提示:
结点的数量会在范围 [2, 15] 内。
你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
再次使用递归的思想,新建方法allPathsSourceTarget(int[][], int),第一个参数表示图,第二个参数表示当前访问到第几个节点。
从第0个节点开始,如果当前是最后一个节点,也就是n等于数组的大小,那么就返回一条路径;否则,为每条路径都添加当前节点的访问;
最后返回的List<List>就是最后的所有的0到n-1的路径。
中文官网题解:
https://leetcode-cn.com/problems/all-paths-from-source-to-target/solution/
个人题解:
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
return allPathsSourceTarget(graph, 0);
}
/**
* 实际处理
*
* @param graph 图
* @param n 当前是第几个节点
* @return 路径
*/
private List<List<Integer>> allPathsSourceTarget(int[][] graph, int n) {
List<List<Integer>> lists = new ArrayList<>();
// 如果当前是最后一个节点,则直接返回一条路径,路径只有当前节点
if (n == graph.length - 1) {
List<Integer> path = new ArrayList<>();
path.add(graph.length - 1);
lists.add(path);
return lists;
}
// 遍历该节点可以通往其他节点的路,将当前节点添加在路径最前
for (int i : graph[n]) {
for (List<Integer> path : allPathsSourceTarget(graph, i)) {
path.add(0, n);
lists.add(path);
}
}
return lists;
}
}
结果:
虽然没有进5ms,不过还是战胜了很多人呀。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有