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为节点最大出度。

转载于:https://www.cnblogs.com/hankunyan/p/11412110.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值