博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] All Paths From Source to Target 从起点到目标点到所有路径
阅读量:7228 次
发布时间:2019-06-29

本文共 2511 字,大约阅读时间需要 8 分钟。

 

Given a directed, acyclic graph of N nodes.  Find all possible paths from node 0 to node N-1, and return them in any order.

The graph is given as follows:  the nodes are 0, 1, ..., graph.length - 1.  graph[i] is a list of all nodes j for which the edge (i, j) exists.

Example:Input: [[1,2], [3], [3], []] Output: [[0,1,3],[0,2,3]] Explanation: The graph looks like this:0--->1|    |v    v2--->3There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

Note:

  • The number of nodes in the graph will be in the range [2, 15].
  • You can print different paths in any order, but you should keep the order of nodes inside one path.

 

这道题给了我们一个无回路有向图,包含N个结点,然后让我们找出所有可能的从结点0到结点N-1的路径。这个图的数据是通过一个类似邻接链表的二维数组给的,最开始的时候博主没看懂输入数据的意思,其实很简单,我们来看例子中的input,[[1,2], [3], [3], []],这是一个二维数组,最外层的数组里面有四个小数组,每个小数组其实就是和当前结点相通的邻结点,由于是有向图,所以只能是当前结点到邻结点,反过来不一定行。那么结点0的邻结点就是结点1和2,结点1的邻结点就是结点3,结点2的邻结点也是3,结点3没有邻结点。那么其实这道题的本质就是遍历邻接链表,由于要列出所有路径情况,那么递归就是不二之选了。我们用cur来表示当前遍历到的结点,初始化为0,然后在递归函数中,先将其加入路径path,如果cur等于N-1了,那么说明到达结点N-1了,将path加入结果res。否则我们再遍历cur的邻接结点,调用递归函数即可,参见代码如下:

 

解法一:

class Solution {public:    vector
> allPathsSourceTarget(vector
>& graph) { vector
> res; helper(graph, 0, {}, res); return res; } void helper(vector
>& graph, int cur, vector
path, vector
>& res) { path.push_back(cur); if (cur == graph.size() - 1) res.push_back(path); else for (int neigh : graph[cur]) helper(graph, neigh, path, res); }};

 

下面这种解法也是递归,不过写法稍有不同,递归函数直接返回结果,这样参数就少了许多,但是思路还是一样的,如果cur等于N-1了,直接将cur先装入数组,再装入结果res中返回。否则就遍历cur的邻接结点,对于每个邻接结点,先调用递归函数,然后遍历其返回的结果,对于每个遍历到的path,将cur加到数组首位置,然后将path加入结果res中即可,这有点像是回溯的思路,路径是从后往前组成的,参见代码如下:

 

解法二:

class Solution {public:    vector
> allPathsSourceTarget(vector
>& graph) { return helper(graph, 0); } vector
> helper(vector
>& graph, int cur) { if (cur == graph.size() - 1) { return { {graph.size() - 1}}; } vector
> res; for (int neigh : graph[cur]) { for (auto path : helper(graph, neigh)) { path.insert(path.begin(), cur); res.push_back(path); } } return res; }};

 

类似题目:

 

转载地址:http://qsdfm.baihongyu.com/

你可能感兴趣的文章
Python字符编码详解
查看>>
Android开发 Firebase动态链接打开APP
查看>>
基于 HTML5 Canvas 的 3D 模型贴图问题
查看>>
让技术不要成为“背锅侠”!
查看>>
dubbo源码分析系列——dubbo的SPI机制源码分析
查看>>
表格单元格td设置宽度无效的解决办法
查看>>
防止视频资源被下载
查看>>
都是并发惹的祸
查看>>
eclipse实现JavaWeb项目 增量打包
查看>>
面试题系列一之 程序生命周期
查看>>
设计模式——观察者模式:气象监测应用
查看>>
NSUserDefaults简介及如何使用 NSUserDefaults 存储自定义对象
查看>>
IntelliJ IDEA搭建SpringBoot
查看>>
深入浅出iOS事件机制
查看>>
hadoop理解
查看>>
Oracle——18用户、角色和权限信息的视图总结
查看>>
WordPress 中的 Debug 模式(调试模式)
查看>>
node下使用express框架,ejs模板引擎
查看>>
搜索:文本的匹配算法
查看>>
Fedora 17 LibreOffice 办公套件的安装与汉化
查看>>