leetcode笔记: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.

二. 题目分析

题目大意是,给定一组机票,用出发机场和到达机场的一对值[from, to]来表示,重建行程的顺序。所有的机票都从JFK(肯尼迪国际机场)出发。

注意:

如果存在多重有效的行程,你应当返回字典序最小的那个。例如,行程["JFK", "LGA"]的字典序比["JFK", "LGB"]要小。
所有的机场用3个大写字母表示(IATA编码)。可以假设所有的机票均至少包含一条有效的行程。

三. 示例代码

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        vector<string> result;
        int n = tickets.size();
        if (n == 0) return result;
        map<string, multiset<string>> temp;

        for (int i = 0; i < n; ++i)
            temp[tickets[i].first].insert(tickets[i].second);

        stack<string> dfs;
        dfs.push("JFK");
        while (!dfs.empty())
        {
            string top = dfs.front();
            if (!temp[top].empty())
            {
                dfs.push(*temp[top].begin());
                // 使用后,删除该机票
                temp[top].erase(temp[top].begin());
            }
            else
            {
                result.push_back(top);
                dfs.pop();
            }
        }
        reverse(result.begin(), result.end());
    }
};
点赞