forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reconstruct-itinerary.cpp
40 lines (36 loc) · 1.26 KB
/
reconstruct-itinerary.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Time: O(t! / (n1! * n2! * ... nk!)), t is the total number of tickets,
// ni is the number of the ticket which from is city i,
// k is the total number of cities.
// Space: O(t)
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, map<string, int>> graph;
for (const auto& ticket : tickets) {
++graph[ticket.first][ticket.second];
}
const string from{"JFK"};
vector<string> ans{from};
routeHelper(from, tickets.size(), &graph, &ans);
return ans;
}
private:
bool routeHelper(const string& from, const int ticket_cnt,
unordered_map<string, map<string, int>> *graph, vector<string> *ans) {
if (ticket_cnt == 0) {
return true;
}
for (auto& to : (*graph)[from]) {
if (to.second) {
--to.second;
ans->emplace_back(to.first);
if (routeHelper(to.first, ticket_cnt - 1, graph, ans)) {
return true;
}
ans->pop_back();
++to.second;
}
}
return false;
}
};