[LeetCode] 332. Reconstruct Itinerary
题目描述
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.
注意
- 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.
分析
开始的想法就是在数组中寻找符合from的to中最小的加入数组中,但是发现有个测例是不通过的,在该测例中这样找无法找到后续的to。
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
const int n = tickets.size();
vector<string> result;
result.push_back("JFK");
int visited[n];
int i, j, pos, size = tickets.size(), count = 0;
string from = "JFK", to;
for (i = 0; i < size; i++) {
visited[i] = 0;
}
while (count != size) {
to = "";
for (j = 0; j < size; j++) {
if (visited[j]) continue;
if (get<0>(tickets[j]) == from) {
if (to == "") {
to = get<1>(tickets[j]);
pos = j;
} else {
if (to > get<1>(tickets[j])) {
to = get<1>(tickets[j]);
pos = j;
}
}
}
}
count++;
visited[pos] = 1;
from = to;
result.push_back(to);
}
return result;
}
};
后来从上网查找思路,找到一个思路是建立一个以from为key的哈希表,然后按照字典序进行DFS查找,相同字典序则从小到大进行选择,直到某处没有可以相连的to那么就找到了想要的路径,这样才把结果依次加入数组,这样数组的信息是反向的,之后对这个路径进行反向输出就可以了。
代码
class Solution {
public:
void DFS(string from) {
while (hashTable[from].size() > 0) {
string to = *hashTable[from].begin();
hashTable[from].erase(hashTable[from].begin());
DFS(to);
}
result.push_back(from);
}
vector<string> findItinerary(vector<pair<string, string>> tickets) {
if(tickets.size() == 0) return {};
for (auto val : tickets) {
hashTable[val.first].insert(val.second);
}
DFS("JFK");
reverse(result.begin(), result.end());
return result;
}
private:
vector<string> result;
unordered_map<string, multiset<string>> hashTable;
};