图形遍历以到达目标顶点

问题描述

我已经解决了以下问题,该问题要求查找从第0个节点到第n-1个节点的所有路径。代码工作正常,但是我对解决方案的时间复杂度感到困惑。我将以下代码的时间复杂度计算为O(V + E),其中V是顶点,E是顶点之间的边。 由于在DFS中我们要遍历V个顶点,并且每个顶点都可以有E个边,所以我认为TC为O(V + E)

但是,根据leetcode解决方案部分,该算法的时间复杂度为O(2 ^ N-1 x N)。 我真的不明白leetcode是如何提出这个TC的。我认为leetcode的时间复杂度不是以下代码的正确时间复杂度。

有人可以帮我弄清楚时间的复杂性吗?

邮政编码查询链接https://leetcode.com/problems/all-paths-from-source-to-target/

问题描述:

给出N个节点的有向无环图。查找从节点0到节点N-1的所有可能路径,并以任意顺序返回它们。 该图如下所示:节点为0、1,...,graph.length-1。graph [i]是存在边(i,j)的所有节点j的列表。

示例图片

enter image description here

public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        path.add(0);
        
        dfs(graph,result,path,0);
        
        return result;
    }

    private void dfs(int[][] graph,List<List<Integer>> result,List<Integer> path,int node) {
        if(node == graph.length-1) {
            result.add(new ArrayList<>(path));
            return;
        }
        
        int[] edges = graph[node];
        
        for(int edge : edges) {
            
            path.add(edge);
            
            dfs(graph,edge);
            
            path.remove(path.size()-1);
        }
    }

解决方法

想象一下最坏的情况:如果i Java Iterative with Stack and Queue,and statistics comparing Iterative vs Recursive speeds 和what's the time complexity / space complexity for this solution?