LeetCode 332. Reconstruct Itinerary

本题是有向图找 Euler Path 的问题。可以用 Hierholzer’s Algorithm for the directed graph

https://www.geeksforgeeks.org/hierholzers-algorithm-directed-graph/

Hierholzer’s Algorithm 的本质和树里的后序遍历很像。对于 Euler Circuit 来说,dfs如果到头了,说明当前这条路径已经构成了一条回路,backtrack回去把别的道路的 circuit 加到当前 circuit 即可。

由于是dfs,所以可以有 Recursive 和 Iterative 两种写法。

Recursive:https://leetcode.com/problems/reconstruct-itinerary/discuss/78835/28ms-C++-beats-100-Short-and-Elegant.

Iterative:https://leetcode.com/problems/reconstruct-itinerary/discuss/78842/C++-non-recursive-O(N)-time-O(N)-space-solution-with-detail-explanations

 

以下代码是 Recursive

class Solution {
public:
    unordered_map<string,priority_queue<string,vector<string>,greater<string>>> graph;
    vector<string> res;
    
    vector<string> findItinerary(vector<vector<string>>& tickets) {
        for (vector<string> &ticket:tickets)
            graph[ticket[0]].push(ticket[1]);
        
        dfs("JFK");
        reverse(res.begin(),res.end());
        return res;
    }
    
    void dfs(string s){
        auto &neighs=graph[s];
        while (!neighs.empty()){
            string neigh=neighs.top(); neighs.pop();
            dfs(neigh);
        }
        res.push_back(s);
    }
};

Hierholzer’s Algorithm 时间复杂度是O(n),本题由于要排序,时间复杂度 O(nlogd),d为节点最大出度。

posted @ 2019-08-26 13:49  約束の空  阅读(196)  评论(0编辑  收藏  举报