Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
reconstruct-itinerary.cpp 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-02-04 22:42 +08:00 . Update reconstruct-itinerary.cpp
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助