作者: 负雪明烛
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. 22-reverseString-Leetcode

    思路:so easy class Solution { public: string reverseString(string s) { int n = s.size(); for(int i=0;i ...

  2. C++类成员初始化列表的构造顺序

    看下面代码, 输出结果是多少呢? class A{ public: A(int k) : j(k), i(j) { } void show() { cout << this->i & ...

  3. [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上)

    [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 目录 [源码解析] PyTorch 分布式 Autograd (5) ---- 引擎(上) 0x00 摘要 0x0 ...

  4. 纯CSS圆环与圆

    1. 两个标签的嵌套: <div class="element1"> <div class="child1"></div> ...

  5. css通配样式初始化(多款,供君自选)

    腾讯官网 body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,fieldset,legend,input,textarea,select{margin:0; ...

  6. Linux信号1

    信号(signal)是一种软中断,他提供了一种处理异步事件的方法,也是进程间唯一的异步通信方式.在Linux系统中,根据POSIX标准扩展以后的信号机制,不仅可以用来通知某进程发生了什么事件,还可以给 ...

  7. 时光网内地影视票房Top100爬取

    为了和艺恩网的数据作比较,让结果更精确,在昨天又写了一个时光网信息的爬取,这次的难度比艺恩网的大不少,话不多说,先放代码 # -*- coding:utf-8 -*-from __future__ i ...

  8. java加密方式

    加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容.大体上分为双向加密和单向加密,而双向加密又分为对称加密和非对称加密(有些 ...

  9. java中super的几种用法,与this的区别

    1. 子类的构造函数如果要引用super的话,必须把super放在函数的首位. class Base { Base() { System.out.println("Base"); ...

  10. 【AWS】【Basis】基础概念

    1.基础服务类型: 1.1. 链接: 官方文档,很详细:https://www.amazonaws.cn/products/#compute_networking/?nc1=f_dr 这个是一个whi ...