LeetCode刷题感想之DFS

     在剑指Offer里专门有一个部分(大概是连续十几题的样子)考察了 DFS ,也就是深度优先遍历,感觉DFS 也是一种套路,只要思路找对,套一下思路也可以了,在这里记录一下。

     在很多Leetcode 的刷题题解里,深度优先都被称为回溯法,所以 DFS 包含了两个部分,遍历下去,回溯回来。

     先说遍历下去。

     简单来说,就是当下一步有多条选择(岔路) 的时候,优先选择一条路走到底或者找到最优解为止,也就是使用递归。

     当路走到底了,回来选择另一条,继续,这就是回溯。

     DFS 的好处是不需要保存搜索过程中的状态,搜索过以后就要回溯,在空间上不需要额外保存搜索记录。

     在 LeetCode 下的常见做法是:

     给出一个 int[][] graph , 给定一些需求,要求返回可能的路径集合,即 List<List<Integer, Integer>>. 在这里,关键字就是可能的全部路径,etc.

     举个例子(当然还是 LeetCode 了 https://leetcode.com/problems/all-paths-from-source-to-target)

     题目给了一个包含 n 个节点的无回路有向图,找出所有可能的从节点 0 到节点 n-1 的路径。以下上题:

  

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        temp.add(0);
        dfs(graph,res,temp,0);
        return res;
        
    }
    
    public void dfs(int[][] graph, List<List<Integer>> res, List<Integer> temp,int level){
        if(level == graph.length-1){
            res.add(new ArrayList<>(temp));
            return;
        }
        for(int tem: graph[level]){
            temp.add(tem);
            dfs(graph,res,temp,tem);
            temp.remove(temp.size()-1);
        }
    }
}

  

     

     

原文地址:https://www.cnblogs.com/spillage/p/15557033.html