作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/all-paths-from-source-to-target/description/

题目描述

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 v
2--->3 There 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,给出的图graph的每个位置对应的是第i个节点能到达的下一个节点的序号位置。比如题中graph[0] = [1,2]表示图的起点0指向了1,2两个节点。

解题方法

回溯法

经典的dfs的题目啊,第一遍没做这个题的原因是没看懂题目。。

直接使用dfs的模板公式即可,要注意的是给出的path默认就带着起点0,每次添加的是下个节点n不是当前节点pos。停止的条件是 pos == len(graph) - 1。

代码:

class Solution(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
res = []
self.dfs(graph, res, 0, [0])
return res def dfs(self, graph, res, pos, path):
if pos == len(graph) - 1:
res.append(path)
return
else:
for n in graph[pos]:
self.dfs(graph, res, n, path + [n])

二刷的时候对这个题写法更简单了,因为题目给出的是有向无环图,到达根节点之后可以继续搜索,但是不可能再次到达终点了。

class Solution(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
res = []
self.dfs(graph, 0, len(graph) - 1, res, [0])
return res def dfs(self, graph, start, end, res, path):
if start == end:
res.append(path)
for node in graph[start]:
self.dfs(graph, node, end, res, path + [node])

在Python代码里面可以随便就生成了新的列表,导致回溯过程看不清楚,但是C++版本的回溯法因为只用了一个res和一个path,所以回溯过程看的很清楚。

class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<int> path;
path.push_back(0);
dfs(graph, 0, graph.size() - 1, path);
return res;
}
private:
vector<vector<int>> res;
void dfs(vector<vector<int>>& graph, int start, int end, vector<int> path) {
if (start == end) {
res.push_back(path);
} else {
for (int node : graph[start]) {
path.push_back(node);
dfs(graph, node, end, path);
path.pop_back();
}
}
}
};

日期

2018 年 3 月 20 日 ————阳光明媚~
2018 年 12 月 2 日 —— 又到了周日

【LeetCode】797. All Paths From Source to Target 解题报告(Python & C++)的更多相关文章

  1. LeetCode 797. All Paths From Source to Target

    题目链接:https://leetcode.com/problems/all-paths-from-source-to-target/description/ Given a directed, ac ...

  2. 【leetcode】797. All Paths From Source to Target

    Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths fro ...

  3. 【leetcode】All Paths From Source to Target

    题目如下: Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, a ...

  4. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  5. 【LeetCode】450. Delete Node in a BST 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 日期 题目地址:https://leetcode ...

  6. 【LeetCode】833. Find And Replace in String 解题报告(Python)

    [LeetCode]833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu ...

  7. 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)

    [LeetCode]129. Sum Root to Leaf Numbers 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/pr ...

  8. 【LeetCode】Longest Word in Dictionary through Deleting 解题报告

    [LeetCode]Longest Word in Dictionary through Deleting 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode. ...

  9. 【LeetCode】380. Insert Delete GetRandom O(1) 解题报告(Python)

    [LeetCode]380. Insert Delete GetRandom O(1) 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxu ...

随机推荐

  1. vector去重--unique

    具体实现见中间源码 function template <algorithm> std::unique equality (1) template <class ForwardIte ...

  2. leetcode刷题之数组NO.4

    1.题目 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数 ...

  3. 工作学习1-tcp自连接

    运维同事反馈服务起不来.下面为了方便,写了一个demo来展示. https://gitee.com/northeast_coder/code/tree/master/case/case1_tcp_se ...

  4. hive向mysql导入数据sqoop命令出错

    报错信息: java.lang.Exception: java.io.IOException: java.lang.ClassNotFoundException: info at org.apache ...

  5. 学习java 7.23

    学习内容: 前面讲解了如果构建GUI界面,其实就是把一些GUI的组件,按照一定的布局放入到容器中展示就可以了.在实际开发中,除了主界面,还有一类比较重要的内容就是菜单相关组件,可以通过菜单相关组件很方 ...

  6. 学习java 7.10

    学习内容: List 集合:有序集合,用户可以精确控制列表中每个元素的插入位置 List 集合特点:有序:存储和取出的元素顺序一致 可重复:存储的元素可以重复 增强for循环:简化数组和 Collec ...

  7. 25. Linux下gdb调试

    1.什么是core文件?有问题的程序运行后,产生"段错误 (核心已转储)"时生成的具有堆栈信息和调试信息的文件. 编译时需要加 -g 选项使程序生成调试信息: gcc -g cor ...

  8. Flink(九)【Flink的重启策略】

    目录 1.Flink的重启策略 2.重启策略 2.1未开启checkpoint 2.2开启checkpoint 1)不设置重启策略 2)不重启 3)固定延迟重启(默认) 4)失败率重启 3.重启效果演 ...

  9. Spark基础:(三)Spark 键值对操作

    1.pair RDD的简介 Spark为包含键值对类型的RDD提供了一些专有的操作,这些RDD就被称为pair RDD 那么如何创建pair RDD呢? 在不同的语言中有着不同的创建方式 在pytho ...

  10. 大数据学习day29-----spark09-------1. 练习: 统计店铺按月份的销售额和累计到该月的总销售额(SQL, DSL,RDD) 2. 分组topN的实现(row_number(), rank(), dense_rank()方法的区别)3. spark自定义函数-UDF

    1. 练习 数据: (1)需求1:统计有过连续3天以上销售的店铺有哪些,并且计算出连续三天以上的销售额 第一步:将每天的金额求和(同一天可能会有多个订单) SELECT sid,dt,SUM(mone ...