Reconstruct Itinerary
https://leetcode.com/problems/reconstruct-itinerary/description/
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.
Thoughts
要求从固定一个点开始,把所有边都走一次且要求路径上排在前面的结点权值尽量小,给定这样的路径一定存在。 欧拉路径,也叫做"一笔画"问题。最直接的思路是从root从权值小的点开始DFS,如果走不通就回溯到另一个子节点。因为这道题要求每个边都走一遍且给定欧拉路径一定存在,也就是说走不通意味着另一边一定能走通:把无向图看成树,右子树最后一个结点能形成环从而回到当前结点并再走一遍左子树以满足欧拉路径一定存在。当左子树可以走通并也形成蹦回root的环时,root和右子树直接看作左子树后面的子树。此时发现通过后序遍历并把遍历过的子节点删除,最后再反转所有结果,能对这两种情况都给出正确解。注意这里的后序遍历不能直接套用以前在二叉树上的iterative后序遍历,原因如图所示:

左边是生产的edge list表示出的节点关系,按照一般后序遍历会得到1231,而想得到的顺序是后序遍历右图得到的3121(=r>1213)。
Code
/*
* @lc app=leetcode id=332 lang=cpp
*
* [332] Reconstruct Itinerary
*/
// @lc code=start
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, multiset<string>> m;
for (const auto &t : tickets) m[t[0]].insert(t[1]);
stack<string> s;
deque<string> res;
s.push("JFK");
while (!s.empty()) {
const auto t = s.top();
if (!m[t].empty()) {
const auto c = *(m[t].begin());
s.push(c);
m[t].erase(m[t].begin());
} else {
s.pop();
res.push_front(t);
}
}
return vector<string> (res.begin(), res.end());
}
};
// @lc code=end
class Solution {
public List<String> findItinerary(String[][] tickets) {
Map<String, PriorityQueue<String>> edges = new HashMap<>();
for (String[] ticket : tickets) {
if (!edges.containsKey(ticket[0])) {
edges.put(ticket[0], new PriorityQueue<>());
}
edges.get(ticket[0]).add(ticket[1]);
}
Stack<String> stack = new Stack<>();
List<String> res = new ArrayList<>();
stack.push("JFK");
while (!stack.isEmpty()) {
String station = stack.peek();
if (edges.containsKey(station) && !edges.get(station).isEmpty()) {
stack.push(edges.get(station).poll());
} else {
stack.pop();
res.add(0,station);
}
}
return res;
}
}
Analysis
每天边遍历一次O(N).
Last updated
Was this helpful?