[leetcode]332. 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 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.
这道题的意思是说有一些飞机票,要从这些票里面恢复出行程,每个行程都是从“JFK”开始的,如果有多种答案,就按照字典序取最小的那个。
乍一看好像挺简单的,每张票做个hash,然后跑一遍就行。
不过存在一个case,比如
[["JFK","KUL"],["JFK“,"NRT"],["NRT","JFK"]]
如果按照字典序,JFK有两个目的地,KUL和NRT。搜索时会先搜索KUL,这样就没后路了,应该要先搜索NRT。对于这个问题,
http://bookshadow.com/weblog/2016/02/05/leetcode-reconstruct-itinerary/的博主的第一种答案给出了方法。设定两个[], left 跟 right,搜索路径的时候如果没有回到出发地的让它靠后,让有出发地的靠前,这样可以保证看起来是合理的行程,其中为了防止在删路径的时候仍然访问删除的路径,还判断了下路径是否还存在着。
import collections
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
dest = collections.defaultdict(list)
for t in tickets:
dest[t[0]].append(t[1])
# for k, v in dest.iteritems():
# dest[k] = sorted(v) def dfs(start):
left, right = [], []
for end in sorted(dest[start]):
if end not in dest[start]:
continue
dest[start].remove(end)
subroute = dfs(end)
if start in subroute:
left += subroute
else:
right += subroute
return [start] + left + right return dfs("JFK")
其中 collections.defaultdict(list) 是内建了一个每次都能直接生成list的dict, 访问这个dict的时候如果没找到就直接生成一个list。
说回来这个问题应该是一个欧拉回路问题,即不重复的把图中所有边都走一遍。对于这个问题,有Hierholzer算法可以求解。
Hierholzer算法把每次访问的节点入栈,若节点无后续可访问的路径,则出栈,这样保持了每一个节点继续被访问的可能性。利用函数调用递归就是栈的特性,直接建立一个dfs函数,用它当栈,于是有:
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
dest = collections.defaultdict(list)
for t in tickets:
dest[t[0]].append(t[1])
for k,v in dest.iteritems():
dest[k]=sorted(v,reverse=True)
route=[]
def dfs(start):
while(dest[start]):
dfs(dest[start].pop())
route.append(start)
dfs("JFK")
return route[::-1]
最后返回这个出栈序列的反。
用c++实现如下:
#include<iostream>
#include<set>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include<string>
using namespace std; class Solution {
public:
unordered_map<string,multiset<string>> dest;
vector<string> route;
void dfs(string start){
while(dest[start].size()>0){
auto pre= &dest[start];
string tmp = *(pre->begin());
pre->erase(pre->begin());
dfs(tmp);
}
route.push_back(start);
}
vector<string> findItinerary(vector<pair<string, string>> tickets){
for(auto e:tickets)
dest[e.first].insert(e.second);
dfs("JFK");
reverse(route.begin(),route.end());
return route;
}
};
其中利用multiset自带有序的特性,直接取出来。unordered_map比起map搜索时间更短,但耗费的空间更大。
总的来说,这道题还是挺有趣的,涉及到的一些知识点包括欧拉回路,Hierholzer算法,DFS等。
[leetcode]332. Reconstruct Itinerary的更多相关文章
- 【LeetCode】332. Reconstruct Itinerary 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 相似题目 参考资料 日期 题目地址:htt ...
- 【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 ...
- 332. Reconstruct Itinerary (leetcode)
1. build the graph and then dfs -- graph <String, List<String>>, (the value is sorted a ...
- 332 Reconstruct Itinerary 重建行程单
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
- 332. Reconstruct Itinerary
class Solution { public: vector<string> path; unordered_map<string, multiset<string>& ...
- [LeetCode] 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 ...
- [Swift]LeetCode332. 重新安排行程 | Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], r ...
随机推荐
- Python练习三
1.使用while和for循环分别打印字符串s=’asdfer’中每个元素. s = "asdfer" index = 0 while index < int(len(s)) ...
- jQuery: 判断from表单是否修改
<script> $(function() { $("#myform :input").change(function(){ $("#myform" ...
- OpenStack控制节点上搭建Q版nova服务(step5)
placement组件监听的端口号是:8778 nova组件监听的端口号是:6080.8774.8775 其中6080端口号是novncproxy监听的端口号. 1.安装服务组件 yum instal ...
- __unsafe_unretained的含义
OC的变量限定词的官方解释: __strong is the default. An object remains “alive” as long as there is a strong point ...
- django orm 管理器 objects
给某张表的管理器重命名 class User(models.Model): name = models.CharField(max_length=100) people = models.Manage ...
- spring boot项目中处理Schedule定时任务
项目中,因为使用了第三方支付(支付宝和微信支付),支付完毕后,第三方支付平台一般会采用异步回调通知的方式,通知商户支付结果,然后商户根据通知内容,变更商户项目支付订单的状态.一般来说,为了防止商户项目 ...
- python中类似三元表达式的写法
python中没有其它语言中的三元表达式,如: a = x > y ? m : n; python中的类似写法为: a = 1 b = 2 h = "" h = " ...
- htm,css,javascript及其他的注释方式
转自:http://www.cnblogs.com/dapeng111/archive/2012/12/23/2829774.html 一.HTML的注释方法<!-- html注释:START ...
- Arrays和String单元测试
20175227张雪莹 2018-2019-2 <Java程序设计> Arrays和String单元测试 要求 在IDEA中以TDD的方式对String类和Arrays类进行学习 测试相关 ...
- Centos7下GlusterFS分布式存储集群环境部署记录
0)环境准备 GlusterFS至少需要两台服务器搭建,服务器配置最好相同,每个服务器两块磁盘,一块是用于安装系统,一块是用于GlusterFS. 192.168.10.239 GlusterFS-m ...