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. 学习笔记TF053:循环神经网络,TensorFlow Model Zoo,强化学习,深度森林,深度学习艺术

    循环神经网络.https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/re ...

  2. 控制使用jquery load()方法载入新页面中的元素

    最近在项目中用到jquery的load()方法来加载页面,首先简单说一下load()方法. load(url,data,callback);该方法接收三个参数,第一个是载入的页面地址,第二个是要传到服 ...

  3. Educational Codeforces Round 54 (Rated for Div. 2) D:Edge Deletion

    题目链接:http://codeforces.com/contest/1076/problem/D 题意:给一个n个点,m条边的无向图.要求保留最多k条边,使得其他点到1点的最短路剩余最多. 思路:当 ...

  4. DNS实战--2

    构建企业级DNS服务压测,服务的功能测试,这些在生产中都要考虑到 1.硬件选型dns对网卡和cpu消耗大下面配置可以达到单台服务器每秒3万请求,0延时CPU:12c以上配置内存:16GB网络:千兆 2 ...

  5. 微信小程序自运营器 微信小程序自动运营器(让你的微信小程序,公众号零运营成本,24小时全自动运营)

    自动发单,自动评价,自动评论,自动推广 微信小程序自运营器  微信小程序自动运营器(让你的微信小程序,公众号零运营成本,24小时全自动运营) 我们会根据你的微信公众号或微信小程序定制开发带有一定AI智 ...

  6. 前端表单提交数据~php获取表单内容

    上图代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www ...

  7. IMU(LPMS-B2) ROS下使用教程

    一.基本信息 http://www.alubi.cn/lpms-b2/ 安装ros教程 http://wiki.ros.org/lpms_imu https://lp-research.com/ros ...

  8. CUDA 编程

    作者:MingChaoSun 原文:https://blog.csdn.net/sunmc1204953974/article/details/51000970 一.CPU和GPU 上图是CPU与GP ...

  9. WIMLIB-CAPTURE捕获说明

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

  10. FBI树-数据结构(二叉树)

    问题 B: [2004_p4]FBI树-数据结构 时间限制: 1 Sec  内存限制: 125 MB提交: 57  解决: 46 题目描述 我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称 ...