[Leetcode] 332. Reconstruct Itinerary 解题报告

本文介绍了一种使用bottom-up DFS算法解决航班行程重构问题的方法。通过建立哈希表存储机票信息,利用multiset自动排序特性确保行程按字典序排列。算法从JFK机场开始,递归寻找所有可能的行程路径,最终返回字典序最小的完整行程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. 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.

思路

这道题目的特殊之处在于需要使用bottom up的DFS,就是路径是反向从最底层网上得出的。我们首先将所有的机票用哈希表给保存起来,最后就是要找一条路径将机票用完,并且如果有多条路径,就找字典序最小的。我们定义的数据结构是multiset<string>来表示哈希表的value,这是因为一方面里面可能会有重复字符串,另一方面multiset自动排序,方便我们有序的读取数据。

接下来我们就从“JFK”机场出发,按照字典序从小到大选取与其连接的地方,从下一个地点再递归的进行搜索,直到没有和某地点相连的机票了。此时我们就到达了最底层,然后往上返回路径即可。

感觉这个代码还是有点不太好理解,欢迎大家在留言中讨论。

代码

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        if(tickets.size() == 0) {
            return result;
        }
        unordered_map<string, multiset<string>> hash;
        for(auto val : tickets) {
            hash[val.first].insert(val.second);
        }
        stack<string> st;       // stores the current possible departing airports
        st.push("JFK");
        while(!st.empty()) {
            string s = st.top();
            if(hash.find(s) != hash.end()) {
                st.push(*hash[s].begin());
                hash[s].erase(hash[s].begin());
                if(hash[s].size() == 0) {
                    hash.erase(s);
                }
            }
            else {              // cannot go to the next airport, so of course it will be the first departure airport
                result.push_back(s);
                st.pop();
            }
        }
        reverse(result.begin(), result.end());
        return result;
    }
private:
    vector<string> result;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值