题目大意:给你一个无环有向图,返回所有从节点0到节点n-1的路径。
Problem:
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.
1 2 3 4 5 6 7 8 9 |
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.
Solution 1: DFS
Time complexity: O(n!)
Space complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Author: Huahua // Running time: 85 ms class Solution { public: vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<vector<int>> ans; vector<int> path(1, 0); dfs(graph, 0, graph.size() - 1, path, ans); return ans; } private: void dfs(const vector<vector<int>>& graph, int cur, int dest, vector<int>& path, vector<vector<int>>& ans) { if (cur == dest) { ans.push_back(path); return; } for (int next : graph[cur]) { path.push_back(next); dfs(graph, next, dest, path, ans); path.pop_back(); } } }; |
“Cleaner” Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Solution { public: vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { vector<vector<int>> ans; vector<int> path{0}; dfs(graph, path, ans); return ans; } private: void dfs(const vector<vector<int>>& graph, vector<int>& path, vector<vector<int>>& ans) { if (path.back() == graph.size() - 1) { ans.push_back(path); return; } for (int next : graph[path.back()]) { path.push_back(next); dfs(graph, path, ans); path.pop_back(); } } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment