题目地址:
https://leetcode.com/problems/reconstruct-itinerary/
给定若干机票的出发城市和到达城市,要求从JFK这个机场出发,用完所有机票,到达另一个城市(也可以回到JFK),并且路径的字典序要最小。返回这个字典序最小的路径上的所有城市的列表。题目保证答案存在。
非递归写法参考https://blog.csdn.net/qq_46105170/article/details/113533700。下面介绍递归写法。
本质上是在求有向图欧拉路径的问题。思路是DFS。从JFK出发做DFS,优先走字典序较小的城市,回溯的时候再将城市加入列表,最后再将列表反个序就是一个字典序最小的欧拉路径。第一次回溯的位置一定是终点的位置,回溯之前再把顶点加进列表,才能把所有的路径上的顶点都加进列表;至于每次取出字典序最小的城市,我们可以用最小堆来做。代码如下:
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& ts) {
vector<string> res;
unordered_map<string, priority_queue<string, vector<string>, greater<>>> g;
for (auto &v : ts) g[v[0]].push(v[1]);
dfs("JFK", g, res);
reverse(res.begin(), res.end());
return res;
}
void dfs(string s, unordered_map<string, priority_queue<string, vector<string>, greater<>>>& g, vector<string>& res) {
if (g.count(s)) {
auto &heap = g[s];
while (heap.size()) {
auto t = heap.top(); heap.pop();
dfs(t, g, res);
}
}
res.push_back(s);
}
};
时间复杂度 O ( V log E ) O(V\log E) O(VlogE),空间 O ( V + E ) O(V+E) O(V+E)。