zoukankan      html  css  js  c++  java
  • LeetCode 797. 所有可能的路径

    题目链接

    797. 所有可能的路径

    题目分析

    这个题,给了一个有向图的背景,然后要求我们把所有满足条件的路径都输出出来,看到返回值上的List<List>,刷题量比较多的人都知道这种一般都是回溯法解决。

    代码实现

    class Solution {
        public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
            boolean[] visited = new boolean[graph.length];
            List<List<Integer>> res = new ArrayList<>();
            List<Integer> temp = new ArrayList<>();
            temp.add(0);
            backTracking(graph,visited,0,res,temp);
            return res;
        }
    
        public void backTracking(int[][] graph, boolean[] visited, int index, List<List<Integer>> res, List<Integer> temp){
            if(visited[index]){
                return;
            }
            if(graph[index].length == 0){
                res.add(new ArrayList<>(temp));
                return;
            }
            visited[index] = true;
            for(int i = 0; i < graph[index].length; i++){
                temp.add(graph[index][i]);
                backTracking(graph,visited,graph[index][i],res,temp);
                temp.remove(temp.size()-1);
            }
    //记得把visited状态还原
            visited[index] = false;
        }
    }
    

    我这里还是使用到了visited数组,我看到评论区中有说连这个数组都不用开的。说明自己还是熟练呀

  • 相关阅读:
    Tips
    react
    Vue 双向绑定
    jQuery 学习笔记
    CC NOV17
    一种高效处理无修改区间或树上询问的数据结构(附代码)
    HNOI 2017
    PA2015
    bzoj 泛做
    GG
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/13195975.html
Copyright © 2011-2022 走看看