LeetCode #332 Reconstruct Itinerary

题目

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.

Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.

解题思路

初看这道题觉得是拓扑排序问题,但是踩过坑后就知道,这是求欧拉路径的问题。而这道题对所求的欧拉路径还添加了一个限制:必须以字典序从小到大输出遍历的结点。
采用贪心的算法,用 N 个小顶堆存储每个结点指向的结点(N 为结点个数),然后从 JFK 结点开始进行 DFS ,每次都对字典序最小的结点进行搜索。当搜索到最后一个结点 E 时,说明已经产生了从 JFKE 的一条路径,则在最后的结果中这条路径肯定是存在的,而对剩下没有搜索到的路径,肯定可以从这条路径上的某个结点扩展出去后搜索到,因此自然就想到要回溯。所以,我们每次到达一条路径的最后结点时,就把这个结点 push_back 进结果集合中,然后回溯到上一个结点继续 DFS ,当 DFS 把所有路径都遍历完毕后,结果结合中的结点是按倒序的方式排列的,我们只需要把结果集合反转就可以了。

c++ 代码实现

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        unordered_map<string, priority_queue<string, vector<string>, greater<string> > > G;
        vector<string> rst;

        for (int i = 0; i < tickets.size(); ++i) {
            G[tickets[i].first].push(tickets[i].second);
        }

        DFS("JFK", G, rst);

        reverse(rst.begin(), rst.end());
        return rst;
    }

    void DFS(string node, unordered_map<string, priority_queue<string, vector<string>, greater<string> > >& G, vector<string>& rst) {
        while (!G[node].empty()) {
            string cur = G[node].top();
            G[node].pop();
            DFS(cur, G, rst);
        }
        rst.push_back(node);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值