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:

  1. 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"].
  2. All airports are represented by three capital letters (IATA code).
  3. 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 ScheduleCourse 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;
}
};

类似题目:

Course Schedule

Course Schedule II

参考资料:

https://leetcode.com/problems/reconstruct-itinerary/

https://discuss.leetcode.com/topic/36370/short-ruby-python-java-c

https://discuss.leetcode.com/topic/36721/short-c-dfs-iterative-44ms-solution-with-explanation-no-recursive-calls-no-backtracking

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Reconstruct Itinerary 重建行程单的更多相关文章

  1. 332 Reconstruct Itinerary 重建行程单

    Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...

  2. LeetCode Reconstruct Itinerary

    原题链接在这里:https://leetcode.com/problems/reconstruct-itinerary/ 题目: Given a list of airline tickets rep ...

  3. Reconstruct Itinerary

    Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...

  4. 【LeetCode】332. Reconstruct Itinerary 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 相似题目 参考资料 日期 题目地址:htt ...

  5. [LeetCode] Reconstruct Original Digits from English 从英文中重建数字

    Given a non-empty string containing an out-of-order English representation of digits 0-9, output the ...

  6. 【LeetCode】Reconstruct Itinerary(332)

    1. Description Given a list of airline tickets represented by pairs of departure and arrival airport ...

  7. 【LeetCode】332. Reconstruct Itinerary

    题目: Given a list of airline tickets represented by pairs of departure and arrival airports [from, to ...

  8. [leetcode]332. Reconstruct Itinerary

    Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...

  9. 332. Reconstruct Itinerary (leetcode)

    1. build the graph and then dfs -- graph <String, List<String>>,  (the value is sorted a ...

随机推荐

  1. 前端精选文摘:BFC 神奇背后的原理

    BFC 已经是一个耳听熟闻的词语了,网上有许多关于 BFC 的文章,介绍了如何触发 BFC 以及 BFC 的一些用处(如清浮动,防止 margin 重叠等).虽然我知道如何利用 BFC 解决这些问题, ...

  2. The Road To Hadoop(网盘系统的实现)

    因为毕业设计的原因,得从零开始学习hadoop.虽然接触Hadoop也有一段时间了,但是没有一个完整的时间段去学习,在公司实习的同时,只能利用零零碎碎的时间学习,今天完成了第一个版本的基于Hadoop ...

  3. Windows下Memcached安装与配置实例

    环境声明: 服务器: Windows Server 2008r2: Memcached: Memcached 64-bit for Windows(64位) From: http://www.urie ...

  4. 记录软件工程课程项目开发时遇到的各种小问题(django)

    1.python manage.py makemigrations 无效/无法检测出model的变化 在修改了models.py之后,我们想要更新数据库的表,使用了python manage.py m ...

  5. 用C#实现MD5的加密(转载)

    方法一 首先,先简单介绍一下MD5 MD5的全称是message-digest algorithm 5(信息-摘要算法,在90年代初由mit laboratory for computer scien ...

  6. 2011奥斯卡最佳纪录片《监守自盗(Inside Job)》小结

    影片探讨了2008年金融危机产生的原因. 美国忽略1933年的旧法律,立新法,以放松金融监管. 投资银行被允许更高的杠杆率,33:1,也就是说,投资物跌价3%就会导致破产. 投资银行放贷,但是转手将贷 ...

  7. Checkbox 模板和样式

    <Style TargetType="{x:Type CheckBox}"> <Setter Property="FontFamily" Va ...

  8. 居然是Firefox没有抛弃我们

    面向企业级市场,一款网页浏览器的很多特性不是说改就改,说丢弃就丢弃.就像微软不能抛弃IE一样,Firefox也有类似的定位和使命. Firefox即尝试提供企业级市场所需的特性稳定的软件版本(LTS) ...

  9. Delphi_04_Delphi_Object_Pascal_基本语法_02

    这里简单的描述Object的语法中的基本内容,数据类型.因为代码是自描述的所以不废话,直接贴代码. { 用户自定义类型 1.数组 2.动态数组 3.记录 4.集合 } program UserDefi ...

  10. 分享一些学习资料-大量PDF电子书

    分享一些学习用的电子书籍,给那些喜欢看书而不一定有机会买书的童鞋. 反对积分下载,提倡自由分享. 分享地址: http://pan.baidu.com/s/1qWK5V0g 提取密码:   np33 ...