-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
36 lines (28 loc) · 956 Bytes
/
main.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
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, int> ticketCount;
unordered_map<string, set<string>> adj;
for (auto& ticket : tickets) {
adj[ticket[0]].insert(ticket[1]);
++ticketCount[ticket[0] + ticket[1]];
}
vector<string> result = {"JFK"};
function<bool()> dfs = [&]() -> bool {
if (result.size() == tickets.size() + 1) return true;
string u = result.back();
for (auto v : adj[u]) {
string ticket = u + v;
if (ticketCount[ticket] == 0) continue;
--ticketCount[ticket];
result.push_back(v);
if (dfs()) return true;
result.pop_back();
++ticketCount[ticket];
}
return false;
};
dfs();
return result;
}
};