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