[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 ...
随机推荐
- bootstrap实现列的拖动
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"& ...
- Excel常用公式
转载请注明来源"ExcelHome"并保留原文链接.固定链接:http://www.excelhome.net/lesson/article/excel/1897.html 1.I ...
- springboot 添加 jsp支持
idea 新建springboot项目 packageing:选择 war next 勾选web 添加jar包 <dependency> <groupId>org.apac ...
- CWMP开源代码研究6——libcwmp动态库开发
原创作品,转载请注明出处,严禁非法转载.如有错误,请留言! email:40879506@qq.com 为了使程序具有通用性,便于扩展和维护.采用了"模块"插入的思想.将设备业务相 ...
- [delphi]在DLL中多线程同步Synchronize卡死问题
在dll中多线程同步调用Synchronize不可以,会出现假死卡住的现象.可通过Sendmessage实现. 转网上其他文章解释: Application.Initialize; begin ...
- 如何快速开发html5跨平台K12/幼儿交互课件、动画课件、交互游戏
flash交互课件能生动表达教学内容,也深受广大教育工作者的喜爱,但是目前flash课件只能在pc电脑平台上进行展示,随着移动网络的发展,越来越多的课件产品需要移殖到各种移动平台(手机,pad,智能电 ...
- Indent Guides插件格式代码
vs开发工具实用性插件 一. 在开发遇到过很多括号缩近的,很是头疼,于是上网收了一下,希望对大家有所帮助. 第一款插件:Indent Guides 这款插件是给代码块增长对齐线,以标识匹配的花括号 ...
- Nginx配置CI框架问题(Linux平台下Centos系统)
CI框架:官方文档 http://codeigniter.org.cn/user_guide/index.html CI框架的数据流程图如下: 其中:index.php作为入口文件,在安装好CI框架后 ...
- SSO单点登录三种情况的实现方式详解
单点登录(SSO——Single Sign On)对于我们来说已经不陌生了.对于大型系统来说使用单点登录可以减少用户很多的麻烦.就拿百度来说吧,百度下面有很多的子系统——百度经验.百度知道.百度文库等 ...
- 集成学习(ensemble learning)
集成学习,又称为“多分类器系统”(multi-classifier system).“基于委员会的学习”(committee-based learning)等.基本的想法是结合多个学习器,获得比单一学 ...