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
.html
Note:java
["JFK", "LGA"]
has a smaller lexical order than ["JFK", "LGB"]
.
Example 1:tickets
= [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"]
.python
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.api
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.ruby
這道題給咱們一堆飛機票,讓咱們創建一個行程單,若是有多種方法,取其中字母順序小的那種方法。這道題的本質是有向圖的遍歷問題,那麼LeetCode關於有向圖的題只有兩道Course Schedule和Course Schedule II,而那兩道是關於有向圖的頂點的遍歷的,而本題是關於有向圖的邊的遍歷。每張機票都是有向圖的一條邊,咱們須要找出一條通過全部邊的路徑,那麼DFS不是咱們的不二選擇。先來看遞歸的結果,咱們首先把圖創建起來,經過鄰接鏈表來創建。因爲題目要求解法按字母順序小的,那麼咱們考慮用multiset,能夠自動排序。等咱們圖創建好了之後,從節點JFK開始遍歷,只要當前節點映射的multiset裏有節點,咱們取出這個節點,將其在multiset裏刪掉,而後繼續遞歸遍歷這個節點,因爲題目中限定了必定會有解,那麼等圖中全部的multiset中都沒有節點的時候,咱們把當前節點存入結果中,而後再一層層回溯回去,將當前節點都存入結果,那麼最後咱們結果中存的順序和咱們須要的相反的,咱們最後再翻轉一下便可,參見代碼以下:post
解法一:this
class Solution { public: vector<string> findItinerary(vector<pair<string, string>> tickets) { vector<string> res; unordered_map<string, multiset<string>> m; for (auto a : tickets) { m[a.first].insert(a.second); } dfs(m, "JFK", res); return vector<string> (res.rbegin(), res.rend()); } void dfs(unordered_map<string, multiset<string>>& m, string s, vector<string>& res) { while (m[s].size()) { string t = *m[s].begin(); m[s].erase(m[s].begin()); dfs(m, t, res); } res.push_back(s); } };
下面咱們來看迭代的解法,須要藉助棧來實現,來實現回溯功能。好比對下面這個例子:url
tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["MRT", "JFK"]]spa
那麼創建的圖以下:code
JFK -> KUL, NRT
NRT -> JFK
因爲multiset是按順序存的,全部KUL會在NRT以前,那麼咱們起始從JFK開始遍歷,先到KUL,可是KUL沒有下家了,這時候圖中的邊並無遍歷完,此時咱們須要將KUL存入棧中,而後繼續往下遍歷,最後再把棧裏的節點存回結果便可,參見代碼以下:
解法二:
class Solution { public: vector<string> findItinerary(vector<pair<string, string>> tickets) { vector<string> res; stack<string> st{{"JFK"}}; unordered_map<string, multiset<string>> m; for (auto t : tickets) { m[t.first].insert(t.second); } while (!st.empty()) { string t = st.top(); if (m[t].empty()) { res.insert(res.begin(), t); st.pop(); } else { st.push(*m[t].begin()); m[t].erase(m[t].begin()); } } return res; } };
相似題目:
參考資料:
https://leetcode.com/problems/reconstruct-itinerary/
https://discuss.leetcode.com/topic/36370/short-ruby-python-java-c