LeetCode 797 All Paths From Source to Target

Tag: 图算法 LeetCode Posted on 2022-02-08 11:26:31 Edited on 2022-02-08 11:32:03 Views: 151

概述

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

递归法

和回溯法很像。

class Solution {
public:
    vector<vector<int>> paths;
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<int> path;
        helper(graph, 0, path);
        return paths;
    }
    
    void helper(vector<vector<int>>& graph, int s, vector<int> path) {
        path.push_back(s);
        
        if (s == graph.size() - 1) {
            paths.push_back(path);
            // return;
        }
        
        for (auto n : graph[s]) {
            helper(graph, n, path);
        }
        
        path.pop_back();
    }
};

真的吗?其实这里根本没有必要弹出,因为你这里的 path 是局部变量,函数结束后就销毁了。

当然,当 path 共享时,就必须弹出了。

class Solution {
public:
    vector<vector<int>> paths;
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        vector<int> path;
        helper(graph, 0, path);
        return paths;
    }
    
    void helper(vector<vector<int>>& graph, int s, vector<int>& path) {
        path.push_back(s);  // 这里自动 copy 了向量
        
        if (s == graph.size() - 1) {
            paths.push_back(path);
        }
        
        for (auto n : graph[s]) {
            helper(graph, n, path);
        }
        
        path.pop_back();
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/