题目:
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.
提示:
这道题看到之后第一反应一般就是使用dfs,不过用法还需要结合题目的要求和图的特性。因为题目要求结果要按照字母大小顺序排序,因此我们在记录每个点能到达的点集时,可以用STL中的unordered_map<string, multiset<string>>, unordered_map效率比map高一些,另外multiset允许同样的值插入多次,且是按序插入的。
然后说说这个图的特性,因为题目说了给定的输入是一定有解的,所以,图中所有的点我们可以按照出度和入度之和的奇偶分成两类:
- 出度和入度之和为奇:这种点最多只有两个,就是起点和终点;
- 出度和入度之和为偶:就是正常的中间过渡点;
- 如果所有点的出度和入度之和都为偶,那么一直dfs到底就是要求的解;
- 在dfs过程中,如果我们stuck了,其实就是因为我们访问到了终点。
上面这几个特性就不一一证明了,可以画个草图简单理解一下。
因此我们在dfs的时候,如果卡住了,那么说明访问到了终点,就把这个点放进vector中。如果没卡住的话,就把点push进stack中(用于回溯),并且一直访问下去,并且经过的点都要记得及时删除,防止走重复的路径。
最后,由于先访问到的“终点”在vector的前端,因此在返回vector前要记得reverse一下。
代码:
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, multiset<string>> m;
vector<string> res;
if (tickets.size() <= ) {
return res;
}
for (pair<string, string> p: tickets) {
m[p.first].insert(p.second); }
stack<string> s;
s.push("JFK");
while (s.size()) {
string next = s.top();
if (m[next].empty()) {
res.push_back(next);
s.pop();
} else {
s.push(*m[next].begin());
m[next].erase(m[next].begin());
}
}
reverse(res.begin(), res.end());
return res;
}
};