【Leetcode】797. All Paths From Source to Target

题目地址:

https://leetcode.com/problems/all-paths-from-source-to-target/

给定一个有向图,顶点编号为 0 ∼ N − 1 0\sim N-1 0N1,以邻接表形式给出。要求返回所有从 0 0 0 N − 1 N-1 N1的路径。题目保证图没有环。

思路是DFS,只需注意递归回溯的时候要恢复现场。代码如下:

class Solution {
 public:
  int n;
  vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& g) {
    n = g.size();
    vector<vector<int>> res;
    vector<int> v;
    dfs(0, v, g, res);
    return res;
  }

  void dfs(int u, vector<int>& path, vector<vector<int>>& g,
           vector<vector<int>>& res) {
    path.push_back(u);
    if (u == n - 1) {
      res.push_back(path);
      path.pop_back();
      return;
    }

    for (int i = 0; i < g[u].size(); i++) dfs(g[u][i], path, g, res);
    path.pop_back();
  }
};

时间复杂度 O ( V + E ) O(V+E) O(V+E),空间复杂度 O ( V ) O(V) O(V)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值