Reconstruct Itinerary
来源:互联网 发布:软件外包公司 知乎 编辑:程序博客网 时间:2024/05/14 00:55
c++
class Solution {public: vector<string> findItinerary(vector<pair<string, string>> tickets) { if (tickets.empty()) return vector<string>(); unordered_map<string, multiset<string>> graph; for (auto &v : tickets) { graph[v.first].insert(v.second); } stack<string> dfs; dfs.push("JFK"); vector<string> res; while (!dfs.empty()){ string cur_node = dfs.top(); if (graph[cur_node].empty()) { res.push_back(cur_node); dfs.pop(); } else { dfs.push(*graph[cur_node].begin()); graph[cur_node].erase(graph[cur_node].begin()); } } reverse(res.begin(), res.end()); return res; }};
python
class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ if not tickets: return [] graph = collections.defaultdict(list) for a, b in sorted(tickets)[::-1]: graph[a].append(b) dfs = ['JFK'] res = [] while dfs: cur_node = dfs[-1] if not graph[cur_node]: res.append(dfs.pop()) else: dfs.append(graph[cur_node].pop()) return res[::-1]
reference:
1\ https://leetcode.com/discuss/85439/short-iterative-solution-explanation-recursive-backtracking
2\ Introduction to Algorithms, Chapter 22: Graph Algorithms
0 0
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- Reconstruct Itinerary
- leetcode Reconstruct Itinerary
- *[LeetCode]332. Reconstruct Itinerary
- 332. Reconstruct Itinerary
- leetcode 332. Reconstruct Itinerary
- LeetCode332. Reconstruct Itinerary
- [LeetCode 332] Reconstruct Itinerary
- 332. Reconstruct Itinerary
- LeetCode 332 : Reconstruct Itinerary
- tengine整合tomcat加上memcached实现高并发、负载均衡、可扩展架构
- #练习#输入学生姓名与成绩,求班级平均分以及最低分学生成绩的姓名,最高成绩及姓名。
- MySQL删除存储过程和函数
- uva439 - Knight Moves(BFS求最短路)
- 安卓中SQLite数据库操作学习
- Reconstruct Itinerary
- redis的高可用搭建
- 【笔记】C#实现快捷键(系统热键)响应的方法
- redis的主从高可用搭建
- iOS之QuarzCore框架介绍
- 学习使用的PL/0编译器增强版PL/0plusplusCompiler(六)扩展if-then-else
- phpstorm配置xdebug
- Android软键盘自动显示,手动控制显示与隐藏
- windows git操作