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 may 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.

这道题给我们一堆飞机票,让我们建立一个行程单,如果有多种方法,取其中字母顺序小的那种方法。这道题的本质是有向图的遍历问题,那么LeetCode关于有向图的题只有两道Course ScheduleCourse Schedule II,而那两道是关于有向图的顶点的遍历的,而本题是关于有向图的边的遍历。每张机票都是有向图的一条边,我们需要找出一条经过所有边的路径,那么DFS不是我们的不二选择。先来看递归的结果,我们首先把图建立起来,通过邻接链表来建立。由于题目要求解法按字母顺序小的,那么我们考虑用multiset,可以自动排序。等我们图建立好了以后,从节点JFK开始遍历,只要当前节点映射的multiset里有节点,我们取出这个节点,将其在multiset里删掉,然后继续递归遍历这个节点,由于题目中限定了一定会有解,那么等图中所有的multiset中都没有节点的时候,我们把当前节点存入结果中,然后再一层层回溯回去,将当前节点都存入结果,那么最后我们结果中存的顺序和我们需要的相反的,我们最后再翻转一下即可,参见代码如下:

解法一:

class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
vector<string> res;
unordered_map<string, multiset<string>> m;
for (auto a : tickets) {
m[a.first].insert(a.second);
}
dfs(m, "JFK", res);
return vector<string> (res.rbegin(), res.rend());
}
void dfs(unordered_map<string, multiset<string>>& m, string s, vector<string>& res) {
while (m[s].size()) {
string t = *m[s].begin();
m[s].erase(m[s].begin());
dfs(m, t, res);
}
res.push_back(s);
}
};

下面我们来看迭代的解法,需要借助栈来实现,来实现回溯功能。比如对下面这个例子:

tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["MRT", "JFK"]]

那么建立的图如下:

JFK -> KUL, NRT

NRT -> JFK

由于multiset是按顺序存的,所有KUL会在NRT之前,那么我们起始从JFK开始遍历,先到KUL,但是KUL没有下家了,这时候图中的边并没有遍历完,此时我们需要将KUL存入栈中,然后继续往下遍历,最后再把栈里的节点存回结果即可,参见代码如下:

解法二:

class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
vector<string> res;
stack<string> st{{"JFK"}};
unordered_map<string, multiset<string>> m;
for (auto t : tickets) {
m[t.first].insert(t.second);
}
while (!st.empty()) {
string t = st.top();
if (m[t].empty()) {
res.insert(res.begin(), t);
st.pop();
} else {
st.push(*m[t].begin());
m[t].erase(m[t].begin());
}
}
return res;
}
};

类似题目:

Course Schedule

Course Schedule II

参考资料:

https://leetcode.com/problems/reconstruct-itinerary/

https://discuss.leetcode.com/topic/36370/short-ruby-python-java-c

https://discuss.leetcode.com/topic/36721/short-c-dfs-iterative-44ms-solution-with-explanation-no-recursive-calls-no-backtracking

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Reconstruct Itinerary 重建行程单的更多相关文章

  1. 332 Reconstruct Itinerary 重建行程单

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

  2. LeetCode Reconstruct Itinerary

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

  3. Reconstruct Itinerary

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

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

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

  5. [LeetCode] Reconstruct Original Digits from English 从英文中重建数字

    Given a non-empty string containing an out-of-order English representation of digits 0-9, output the ...

  6. 【LeetCode】Reconstruct Itinerary(332)

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

  7. 【LeetCode】332. Reconstruct Itinerary

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

  8. [leetcode]332. Reconstruct Itinerary

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

  9. 332. Reconstruct Itinerary (leetcode)

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

随机推荐

  1. 【目录】JVM目录

    JVM学习目录 为了方便园友,现对JVM序列笔记做了归档,园友们可以一口气读完整个JVM的笔记 1. [JVM]JVM系列之JVM体系(一) 2. [JVM]JVM系列之垃圾回收(二) 3. [JVM ...

  2. JAVA基础培训(isoft)

    我们

  3. SQLite Expert Professional 3查看SQLite数据

    通常在android进行SQLite数据库的处理查看很不方便,于是自己下载了一个SQLite Expert Professional 3可视化工具用来进行查询数据,由于时间问题就不多说了,直接讲使用方 ...

  4. sencha ext js 6 入门

    Sencha Ext JS号称是目前世界上最先进和最强大的.支持多平台多设备的JavaScript应用程序开发框架.首先看一下Ext JS的发展简史. 1 Ext JS发展简史 YUI-Ext的作者J ...

  5. 用canvas绘制折线图

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. 从Java String实例来理解ANSI、Unicode、BMP、UTF等编码概念

    转(http://www.codeceo.com/article/java-string-ansi-unicode-bmp-utf.html#0-tsina-1-10971-397232819ff9a ...

  7. Android多媒体框架图

    Android多媒体整体架构图 MediaPlayer框架图 Camera框架图 SoundRecorder框架图 VideoCamera框架图 OpenCore与Skia ALSA Audio框架图 ...

  8. swift-元组

    元组: 将多个相同或者不同类型的值用一个小括号括起来就是一个元组.元组和结构体很像,实际上元组是复合类型.小括号内可以写任意类型,如果不定义类型,可以根据数据自动判断推算出类型 省略了类型 let p ...

  9. Appfuse:添加自定义页面组件

    我之前是做ASP.NET的,碰到被多个页面都使用的类似组件后,就想着采用ascx(用户自定义组件)来解决,那做Java我也想用这种方案. 我要做的效果如下: 实现方案:tag方式(自定义标签) 1. ...

  10. prompt() 方法,弹框带输入框

    prompt() 有alert的风格,却带着输入框,这是怎么实现的呢? 语法 prompt(text,defaultText) 参数 描述 text 可选.要在对话框中显示的纯文本(而不是 HTML ...