作者: 负雪明烛
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. PL\SQL和PL/SQL Developer 12安装与配置

    安装: (1)在已有安装包的情况下,直接将安装包解压到文件夹下,注意不要解压缩到c:\programs Files(x86)的文件夹下,不能解压缩到有中文文件夹命名的文件夹下面 (2)没有安装包的情况 ...

  2. LeetCode子矩形查询

    LeetCode 子矩形查询 题目描述 请你实现一个类SubrectangleQueries,它的构造函数的参数是一个rows * cols的矩形(这里用整数矩阵表示),并支持以下两种操作: upda ...

  3. k8s使用ceph的rbd作后端存储

    k8s使用rbd作后端存储 k8s里的存储方式主要有三种.分别是volume.persistent volumes和dynamic volume provisioning. volume: 就是直接挂 ...

  4. Linux下删除的文件如何恢复

    Linux下删除的文件如何恢复 参考自: [1]linux下误操作删除文件如何恢复 [2]Linux实现删除撤回的方法 以/home/test.txt为例 1.df -T 文件夹 找到当前文件所在磁盘 ...

  5. android studio 使用 aidl(二)异步回调

    基础使用请移步 android studio 使用 aidl (一) 首先建立在server端建立两个aidl文件 ITaskCallback.aidl 用于存放要回调client端的方法 // IT ...

  6. linux vi(vim)常用命令汇总(转)

    前言 首先解析一个vim vi是unix/linux下极为普遍的一种文本编辑器,大部分机器上都有vi的各种变种,在不同的机器上常用不同的变种软件,其中vim比较好用也用的比较广泛.vim是Vi Imp ...

  7. github单独下载某一个文件夹

    可以借助svn工具进行下载,实现只下载repo下的指定文件夹内容 背景 需要下载这个文件夹下所有内容https://github.com/rabbitmq/rabbitmq-tutorials/tre ...

  8. node.js require() 源码解读

    时至今日,Node.js 的模块仓库 npmjs.com ,已经存放了15万个模块,其中绝大部分都是 CommonJS 格式.这种格式的核心就是 require 语句,模块通过它加载.学习 Node. ...

  9. matplotlib subplot 多图合一

    1:第一种方法 # method1: subplot2grid ################# ''' 第一个参数(3, 3) 是把图分成3行3列 第二个参数是位置 (0, 0)表示从0行0列开始 ...

  10. drone使用git tag作为镜像tag

    官方自动tag plugin/docker 已支持自动标签,使用方法如下 steps: - name: docker image: plugins/docker settings: repo: foo ...