【LeetCode】332. Reconstruct Itinerary 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/reconstruct-itinerary/description/
题目描述
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 form at least one valid itinerary.
Example 1:
Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
But it is larger in lexical order.
题目大意
重新安排行程,使得给出的所有航班都得经过一次。如果出现多条可行的路径,那么优先选择的字典序最小的航班路径。出发点一定是JFK,而且题目保证了最少有一个可行的遍历路径。
解题方法
后序遍历
感觉是我自己太菜鸡了,看到花花神一般的解法,感觉自己永远不可能想出来的。
这道题的本质是计算一个最"小"的欧拉路径(Eulerian path)。对于一个节点(当然先从JFK开始),贪心地访问最小的邻居,访问过的边全部删除。当碰到死路的时候就回溯到最近一个还有出路的节点,然后把回溯的路径放到最后去访问,这个过程和后序遍历的一样。1. 如果子节点没有死路(每个节点都只左子树),前序遍历便是欧拉路径。2. 如果子节点1是死路,子节点2完成了遍历,那么子节点2先要被访问。1,2都和后序遍历的顺序正好相反。
其中,如果碰到死路,而没有把所有的边都走过一遍的话,就说明这种走法不满足itinerary,需要沿着树根向上找到最近的一个有其他路可以走的节点N,把新的路走一遍。因为题目保证一定存在一条满足要求的itinerary路径,那么一条这样的死路,一定会相对的在这个节点N上存在另一条路,这条路存在一个回到该节点N的环。先把这个环走过之后再去走这条死路,就可以保证把以N为树根的这个路径上的所有点都走到。
首先肯定是要把路径保存成链表法表示的图的。然后对每个顶点的所有邻接顶点进行排序,这样我们每次都优先选择字典序最小的那个顶点作为下次遍历的节点。我们做了后序遍历即可。最后还要把后序遍历的结果再翻转,才是从根节点出发到每个位置的路径。
最坏时间复杂度是O(VlogV),空间复杂度是O(E).
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
graph = collections.defaultdict(list)
for frm, to in tickets:
graph[frm].append(to)
for frm, tos in graph.items():
tos.sort(reverse=True)
res = []
self.dfs(graph, "JFK", res)
return res[::-1]
def dfs(self, graph, source, res):
while graph[source]:
v = graph[source].pop()
self.dfs(graph, v, res)
res.append(source)
相似题目
参考资料
https://www.youtube.com/watch?v=4udFSOWQpdg
日期
2018 年 10 月 30 日 —— 啊,十月过完了
【LeetCode】332. Reconstruct Itinerary 解题报告(Python)的更多相关文章
- [leetcode]332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- 【LeetCode】120. Triangle 解题报告(Python)
[LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...
- LeetCode 1 Two Sum 解题报告
LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...
- 【LeetCode】Permutations II 解题报告
[题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...
- 【LeetCode】Island Perimeter 解题报告
[LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...
- 【LeetCode】01 Matrix 解题报告
[LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...
- 【LeetCode】Largest Number 解题报告
[LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...
- 【LeetCode】Gas Station 解题报告
[LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...
- LeetCode: Unique Paths II 解题报告
Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution Fol ...
随机推荐
- A Child's History of England.13
Then came the boy-king, Edgar, called the Peaceful, fifteen years old. Dunstan, being still the real ...
- A Child's History of England.30
CHAPTER 10 ENGLAND UNDER HENRY THE FIRST, CALLED FINE-SCHOLAR Fine-scholar, on hearing of the Red Ki ...
- 零基础学习java------30---------wordCount案例(涉及到第三种多线程callable)
知识补充:多线程的第三种方式 来源:http://www.threadworld.cn/archives/39.html 创建线程的两种方式,一种是直接继承Thread,另外一种就是实现Runnabl ...
- Angular 组件通信的三种方式
我们可以通过以下三种方式来实现: 传递一个组件的引用给另一个组件 通过子组件发送EventEmitter和父组件通信 通过serive通信 1. 传递一个组件的引用给另一个组件 Demo1 模板引用变 ...
- JavaScript的数据结构快速学-链表的实现
1-单项链表 function LinkedList() { let Node = function(element) { // 辅助类,表示要添加到链表中的项 this.element = elem ...
- Output of C++ Program | Set 11
Predict the output of following C++ programs. Question 1 1 #include<iostream> 2 using namespac ...
- jquery总结和注意事项
1.关于页面元素的引用通过jquery的$()引用元素包括通过id.class.元素名以及元素的层级关系及dom或者xpath条件等方法,且返回的对象为jquery对象(集合对象),不能直接调用dom ...
- maven 是什么?
在了解maven的概念之前,我一直都在项目中使用maven,但是对于maven的了解,只能说连个皮毛都算不上,一直到项目中,自己机械化的deploy项目的时候,发现报错,赶紧报告开发组长,这私服是不是 ...
- java中子类继承父类什么?
1.继承public和protected修饰的属性和方法,不管子类和父类是否在同一个包: 2.继承默认权限修饰符修饰的属性和方法,前提是子类和父类在同一个包.
- 【C/C++】例题3-6 环状序列/算法竞赛入门经典/数组和字符串
[字典序比较] 对于两个字符串,比较字典序,从第一个开始,如果有两位不一样的出现,那么哪个的ASCII码小,就是字典序较小.如果都一样,那么短的小. [题目] 输入一个环状串,输出最小的字典序序列. ...