代码随想录:重新安排行程
回溯的部分是不难的,主要难在设计数据结构
class Solution {
public:
unordered_map<string, map<string, int>> targets;
vector<string> res;
vector<string> findItinerary(vector<vector<string>>& tickets) {
for (vector<string> vec : tickets) {
targets[vec[0]][vec[1]]++;
//第一个括号内是第一层map的key,第二个括号内是第二层map的key
}
res.push_back("JFK");
bt(tickets);
return res;
}
bool bt(vector<vector<string>>& tickets) {
if(res.size()==tickets.size()+1){
return true;
}
//在map中找res结尾的那一个
for(auto& target:targets[res[res.size()-1]]){
//存在
if(target.second>0){
res.push_back(target.first);
target.second--;
if(bt(tickets))return true;
res.pop_back();
target.second++;
}
}
//没找到
return false;
}
};

浙公网安备 33010602011771号