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:

  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:

Input: tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.

 

解题思路:

因为要按照字母顺序排序

所以我们可以用multiset来存储终点,这样可以允许重复并且按照字母顺序排序。

参考了GrandYang的思路

 

 

代码:

class Solution {
public:
    vector<string> findItinerary(vector<pair<string, string>> tickets) {
        unordered_map<string, multiset<string>> m;
        vector<string> ret;
        for(auto t : tickets){
            m[t.first].insert(t.second);
        }
        dfs(m, "JFK", ret);
        return vector<string> (ret.rbegin(), ret.rend());
    }

private:
    void dfs(unordered_map<string, multiset<string>> &m, string cur, vector<string> &ret){
        while(m[cur].size()){
            string next = *m[cur].begin();
            m[cur].erase(m[cur].begin());
            dfs(m, next, ret);
        }
        ret.push_back(cur);
    }
};

 

posted @ 2018-07-05 09:03  妖域大都督  阅读(146)  评论(0编辑  收藏  举报