[LeetCode] Reconstruct Itinerary 重建行程单
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
- If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary
["JFK", "LGA"]has a smaller lexical order than["JFK", "LGB"]. - All airports are represented by three capital letters (IATA code).
- You may assume all tickets may form at least one valid itinerary.
Example 1:tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
这道题给我们一堆飞机票,让我们建立一个行程单,如果有多种方法,取其中字母顺序小的那种方法。这道题的本质是有向图的遍历问题,那么LeetCode关于有向图的题只有两道Course Schedule和Course Schedule II,而那两道是关于有向图的顶点的遍历的,而本题是关于有向图的边的遍历。每张机票都是有向图的一条边,我们需要找出一条经过所有边的路径,那么DFS不是我们的不二选择。先来看递归的结果,我们首先把图建立起来,通过邻接链表来建立。由于题目要求解法按字母顺序小的,那么我们考虑用multiset,可以自动排序。等我们图建立好了以后,从节点JFK开始遍历,只要当前节点映射的multiset里有节点,我们取出这个节点,将其在multiset里删掉,然后继续递归遍历这个节点,由于题目中限定了一定会有解,那么等图中所有的multiset中都没有节点的时候,我们把当前节点存入结果中,然后再一层层回溯回去,将当前节点都存入结果,那么最后我们结果中存的顺序和我们需要的相反的,我们最后再翻转一下即可,参见代码如下:
解法一:
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
vector<string> res;
unordered_map<string, multiset<string>> m;
for (auto a : tickets) {
m[a.first].insert(a.second);
}
dfs(m, "JFK", res);
return vector<string> (res.rbegin(), res.rend());
}
void dfs(unordered_map<string, multiset<string>>& m, string s, vector<string>& res) {
while (m[s].size()) {
string t = *m[s].begin();
m[s].erase(m[s].begin());
dfs(m, t, res);
}
res.push_back(s);
}
};
下面我们来看迭代的解法,需要借助栈来实现,来实现回溯功能。比如对下面这个例子:
tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["MRT", "JFK"]]
那么建立的图如下:
JFK -> KUL, NRT
NRT -> JFK
由于multiset是按顺序存的,所有KUL会在NRT之前,那么我们起始从JFK开始遍历,先到KUL,但是KUL没有下家了,这时候图中的边并没有遍历完,此时我们需要将KUL存入栈中,然后继续往下遍历,最后再把栈里的节点存回结果即可,参见代码如下:
解法二:
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
vector<string> res;
stack<string> st{{"JFK"}};
unordered_map<string, multiset<string>> m;
for (auto t : tickets) {
m[t.first].insert(t.second);
}
while (!st.empty()) {
string t = st.top();
if (m[t].empty()) {
res.insert(res.begin(), t);
st.pop();
} else {
st.push(*m[t].begin());
m[t].erase(m[t].begin());
}
}
return res;
}
};
类似题目:
参考资料:
https://leetcode.com/problems/reconstruct-itinerary/
https://discuss.leetcode.com/topic/36370/short-ruby-python-java-c
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Reconstruct Itinerary 重建行程单的更多相关文章
- 332 Reconstruct Itinerary 重建行程单
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- LeetCode Reconstruct Itinerary
原题链接在这里:https://leetcode.com/problems/reconstruct-itinerary/ 题目: Given a list of airline tickets rep ...
- Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- 【LeetCode】332. Reconstruct Itinerary 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 相似题目 参考资料 日期 题目地址:htt ...
- [LeetCode] Reconstruct Original Digits from English 从英文中重建数字
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the ...
- 【LeetCode】Reconstruct Itinerary(332)
1. Description Given a list of airline tickets represented by pairs of departure and arrival airport ...
- 【LeetCode】332. Reconstruct Itinerary
题目: Given a list of airline tickets represented by pairs of departure and arrival airports [from, to ...
- [leetcode]332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- 332. Reconstruct Itinerary (leetcode)
1. build the graph and then dfs -- graph <String, List<String>>, (the value is sorted a ...
随机推荐
- 跨域之同源策略 Same-origin policy
同源策略是浏览器中最基本的隔离潜在恶意文件的安全策略,他限制了来自不同源(origin)的文档或脚本之间的相互作用. 何谓同源 在跨域之URL中介绍过一个URL的标准格式如下: 协议类型://服务器地 ...
- WriteLog
public class WriteLog { /// <summary> /// 创建日志文件 /// </summary& ...
- php分页原理
<?php //包含连接MySQL的文件 include "conn.php"; //分页的相关变量 $pagesize = 5; //每页显示条数 //获取地址栏中传递的p ...
- 【IOS开发笔记02】学生管理系统
端到端的机会 虽然现在身处大公司,但是因为是内部创业团队,产品.native.前端.服务器端全部坐在一起开发,大家很容易做零距离交流,也因为最近内部有一个前端要转岗过来,于是手里的前端任务好像可以抛一 ...
- dialog 模块化窗口
xDialog 方法 说明 参数 modal(opts) 模块化弹窗 opts={ title:'标题' , width : '宽度(400)', height : '高度(300)', button ...
- 了解JavaScript 对象属性的标签
对象属性的标签 value(属性值), writable(属性可写), enumerable(属性可枚举), configurable(属性可配置), 这些属性标签使对象所持有的属性体现出不同的特性, ...
- ORA-02020 : 过多的数据库链接在使用中-Windows环境解决步骤
一.现象 编译存储过程时报ORA-02020错误. 错误详细信息:ORA-04052在查找远程对象 xx@yy时出错 ORA-00604 : 递归 SQL 级别 1 出现错误 ORA-02020 : ...
- 多值(in),范围值(between..and)
多值检测 关键词[in] 查出年龄是23,24,28 的人员信息 select * from T_Employee where FAge in (23,25,28) in 后面如果跟子查询, ...
- JavaScript (If...Else和Switch和循环遍历) 语句以及常用消息框
If...Else 语句 JavaScript中if...else语句和Java中的语法和使用方法是一样的. 只是在JavaScript中要使用小写字母.使用大写的 IF 会出错! 至于if...el ...
- EasyUI combobox
高度自适应 data-options="required:true,editable:false,panelHeight:'auto',panelMaxHeight:170" 加上 ...