class Solution {
public:
void dfs(std::unordered_map<std::string, std::vector<std::pair<std::string, bool>>> &tick, vector<std::string> &ret,int &num) {
std::string from = ret.back();
if (tick.count(from) <= 0)
return ;
for (auto &it : tick[from]) {
if (it.second == false) {
from = it.first;
it.second = true;
ret.push_back(from);
dfs(tick, ret,num);
if (ret.size() >= num)
return;
ret.erase(--ret.end());
it.second = false;
}
}
return ;
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
std::unordered_map<std::string, std::vector<std::pair<std::string,bool>>> tick;
vector<string> ret;
for (auto it :tickets){
tick[it[0]].push_back(std::make_pair(it[1], false));// = false;
}
for (auto &it:tick){
std::sort(it.second.begin(), it.second.end());
}
std::string from = "JFK";
ret.push_back(from);
int num = tickets.size();
dfs(tick, ret,num);
return ret;
}
};
leetcode 332. 重新安排行程sort +dfs
最新推荐文章于 2024-09-25 10:36:42 发布