题目:
代码(首刷看解析 2024年2月6日):
cpp
class Solution {
private:
unordered_map<string,map<string,int>> targets;
public:
bool backtracking(int tickNum, vector<string>& res) {
if (tickNum == res.size() - 1) {
return true;
}
for (pair<const string,int>& target : targets[res[res.size() - 1]]) {
if (target.second > 0) {
res.push_back(target.first);
target.second--;
if (backtracking(tickNum, res)) return true;
target.second++;
res.pop_back();
}
}
return false;
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
targets.clear();
vector<string> res;
for (const vector<string>& vec : tickets) {
targets[vec[0]][vec[1]]++;
}
res.push_back("JFK");
backtracking(tickets.size(), res);
return res;
}
};