• 797. All Paths From Source to Target


    问题:

    给定一个【0~n-1】n个节点构成的有向图,

    求从0到n-1的所有路径。

    graph[i]=[a,b,c...]

    指:节点i 指向 节点a,b,c...

    Example 1:
    Input: graph = [[1,2],[3],[3],[]]
    Output: [[0,1,3],[0,2,3]]
    Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
    
    Example 2:
    Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
    Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
    
    Example 3:
    Input: graph = [[1],[]]
    Output: [[0,1]]
    
    Example 4:
    Input: graph = [[1,2,3],[2],[3],[]]
    Output: [[0,1,2,3],[0,2,3],[0,3]]
    
    Example 5:
    Input: graph = [[1,3],[2],[3],[]]
    Output: [[0,1,2,3],[0,3]] 
    
    Constraints:
    n == graph.length
    2 <= n <= 15
    0 <= graph[i][j] < n
    graph[i][j] != i (i.e., there will be no self-loops).
    The input graph is guaranteed to be a DAG.
    

     Example 1:

     Example 2:

    解法:Backtracking(回溯算法)

    • 状态:到当前节点为止,加入的路径path。
    • 选择:当前节点 i 的下一个节点 graph[i] list
      • 当前节点:path的最后一位。
    • 退出递归条件:path的最后一位=n-1

    代码参考:

     1 class Solution {
     2 public:
     3     void dfs(vector<vector<int>>& res, vector<int>& path, vector<vector<int>>& graph, int pos) {
     4         if(path[pos]==graph.size()-1) {
     5             res.push_back(path);
     6             return;
     7         }
     8         if(pos==graph.size()) {
     9             return;
    10         }
    11         for(int nxt:graph[path[pos]]) {
    12             path.push_back(nxt);
    13             dfs(res, path, graph, pos+1);
    14             path.pop_back();
    15         }
    16         return;
    17     }
    18     vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
    19         vector<vector<int>> res;
    20         vector<int> path(1,0);
    21         dfs(res, path, graph, 0);
    22         return res;
    23     }
    24 };
  • 相关阅读:
    java web项目防止多用户重复登录解决方案
    java提高篇(二一)-----ArrayList
    转:为什么需要htons(), ntohl(), ntohs(),htons() 函数
    转:对于linux下system()函数的深度理解(整理)
    转:sprintf与snprintf
    转: fscanf()函数详解
    转:fopen()函数
    转:struct sockaddr与struct sockaddr_in ,struct sockaddr_un的区别和联系
    转:BZERO()等的区别
    转:Linux内存管理之mmap详解
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14338092.html
Copyright © 2020-2023  润新知