代码拉取完成,页面将自动刷新
// 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;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。