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 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的更多相关文章

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

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

  2. 【LeetCode】Reconstruct Itinerary(332)

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

  3. 【LeetCode】332. Reconstruct Itinerary

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

  4. 332. Reconstruct Itinerary (leetcode)

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

  5. 332 Reconstruct Itinerary 重建行程单

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

  6. 332. Reconstruct Itinerary

    class Solution { public: vector<string> path; unordered_map<string, multiset<string>& ...

  7. [LeetCode] Reconstruct Itinerary 重建行程单

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

  8. LeetCode Reconstruct Itinerary

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

  9. [Swift]LeetCode332. 重新安排行程 | Reconstruct Itinerary

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

随机推荐

  1. Development descriptor

    部署描述符指的是配置文件对于一个假象部署到一些容器/发动机. 在Java平台,企业版部署描述符描述组件.模块或应用程序(例如web应用程序或者企业应用程序)应该被部署.它指导部署工具部署具有特定容器选 ...

  2. MySQL Hardware--网络测试

    使用Ping测试丢包 ## ping测试 ## -c 100表示100次 ping -c 100 192.168.1.2 输出结果: ping -c 100 192.168.1.2 PING 192. ...

  3. Elasticsearch(单节点)

    1 Elasticsearch搭建 1.1 通过Wget下载ElasticSearch安装包wget https://artifacts.elastic.co/downloads/elasticsea ...

  4. git的基本应用(一)

    Git常用的命令: mkdir  文件夹名称           创建文件夹 git  init                     将文件夹交个git管理 ls -ah              ...

  5. 网络工具之chisel + openvpn混合

    目的: 访问内网的shared folder 内网可以无缝访问internet而不需要设置代理(因为有些软件没办法支持代理,比如rustup) 解决方案: 基本思路 家里 设置chisel服务开放44 ...

  6. 一台电脑支持2个git账号:gitlab+github

    一.背景 1.公司使用gitlab保存代码,git已支持. 2.需要新增一个人github账户.创建study项目并提交到github上. 3.git提交时互相不混淆 二.操作流程 1.注册githu ...

  7. AMQP close-reason, initiated by Peer, code=406

    错误: AMQPclose-reason, initiated by Peer, code=406, text="PRECONDITION_FAILED -inequivalent arg ...

  8. python3-基础8

    模块与包 什么是模块 模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. #在python中,模块的使用方式都是一样的,但其实细说的话,模块可以分为四个通用类别: 1 ...

  9. WIMLIB-CAPTURE捕获说明

    WIMLIB-CAPTURE捕获说明1.如果捕获目录Y:\windows,那么[ExclusionList]字段里面不能有\windows,否则什么都不能捕捉,但是可以有下面的子目录例如\window ...

  10. ELK + Filebeat 日志分析系统

    ELK + Filebeat 日志分析系统 架构图 环境 OS:CentOS 7.4 Filebeat: 6.3.2 Logstash: 6.3.2 Elasticsearch 6.3.2 Kiban ...