797.所有可能的路径

797.所有可能的路径
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)

二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。

示例:
输入: [[1,2], [3], [3], []]
输出: [[0,1,3],[0,2,3]]
解释: 图是这样的:
0—>1
| |
v v
2—>3
这有两条路: 0 -> 1 -> 3 和 0 -> 2 -> 3.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        return AllPathsSourceTarget(graph,0);
    }
    private List<List<Integer>> AllPathsSourceTarget(int[][] graph,int n)
    {    
        List<List<Integer>> lists = new ArrayList<>();
        if(n==graph.length-1){
        List<Integer> path = new ArrayList<>();
        path.add(graph.length-1);
        lists.add(path);
        return lists;
        }
        for(int i : graph[n])
            for(List<Integer> path : AllPathsSourceTarget(graph,i))
            {path.add(0,n);
            lists.add(path);
        }
        
        return lists;
    }
    
}
发布了27 篇原创文章 · 获赞 2 · 访问量 755

猜你喜欢

转载自blog.csdn.net/qq_44028171/article/details/98755557