leetcode 797.所有可能的路径

思路:dfs。

其实很简单,我们只需要和昨天做的题一样,直接遍历所给数组中的元素,因为这里的数组意义已经很清楚了,就是当前位置的结点和哪一个顶点有联系。

注意:在存储路径的时候,我们需要按顺序存储,而不能在状态标志完之后再统计路径,这样的话顺序是不对的。

class Solution {
public:
vector<int>ans;
void init(){
    ans.push_back(0);
}
void dfs(int u,vector<vector<int>>&s,vector<bool>&st,vector<vector<int>>&res){
    if(u>s.size())return;
    if(u==s.size()-1){
        res.push_back(ans);
        return;
    }
    for(int i=0;i<s[u].size();i++){
        int num=s[u][i];
        if(!st[num]){
            st[num]=1;
            ans.push_back(num);
            dfs(num,s,st,res);
            if(ans.size()>=2)
            ans.pop_back();
            st[num]=0;
        }
    }
}
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        int n=graph.size();
        vector<bool>st(n,false);
        vector<vector<int>>res;
        st[0]=true;
        init();
        dfs(0,graph,st,res);
        return res;
    }
};

相关推荐

  1. leetcode 797.所有可能路径

    2024-05-12 19:44:04       34 阅读
  2. 797. 所有可能路径

    2024-05-12 19:44:04       133 阅读
  3. 图论第一天|797.所有可能路径 200. 岛屿数量

    2024-05-12 19:44:04       67 阅读
  4. leetcode257.二叉树所有路径

    2024-05-12 19:44:04       42 阅读
  5. LeetCode 257. 二叉树所有路径

    2024-05-12 19:44:04       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-12 19:44:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-12 19:44:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-12 19:44:04       87 阅读
  4. Python语言-面向对象

    2024-05-12 19:44:04       96 阅读

热门阅读

  1. 软件工程与软件质量

    2024-05-12 19:44:04       31 阅读
  2. python.完数和斐波那契数列

    2024-05-12 19:44:04       37 阅读
  3. sso单点登录

    2024-05-12 19:44:04       35 阅读
  4. Dockerfile 基本结构

    2024-05-12 19:44:04       37 阅读
  5. 在Mac环境下打包Python应用

    2024-05-12 19:44:04       28 阅读
  6. Spring核心知识点

    2024-05-12 19:44:04       43 阅读
  7. Docker

    Docker

    2024-05-12 19:44:04      30 阅读
  8. ELEC362Application Development with

    2024-05-12 19:44:04       30 阅读