LeetCode 332. Reconstruct Itinerary【medium】

来源:互联网 发布:拾柒网络 编辑:程序博客网 时间:2024/06/06 21:00

原题:

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.

题解:

/*#include <iostream>#include<vector>#include<string>#include<map>#include<set>using namespace std;*/map<string, multiset<string>> targets;vector<string> route;void visit(string target){while (targets[target].size()){string nextTarget = *targets[target].begin();targets[target].erase(targets[target].begin());visit(nextTarget);}route.push_back(target);}vector<string> findItinerary(vector<pair<string, string>> tickets) {for (auto ticket : tickets){targets[ticket.first].insert(ticket.second);}visit("JFK");return vector<string>(route.rbegin(), route.rend());}/*int main(){vector<pair<string, string> > tickets1 = { make_pair("J", "K"), make_pair("J", "N"), make_pair("N", "J"), make_pair("J", "N"), make_pair("N", "P"), make_pair("P", "J") };//vector<pair<string, string> > tickets1 = { make_pair("JFK", "ATL"), make_pair("ATL", "JFK") };vector<string> v = findItinerary(tickets1);for (auto airport : v)cout << airport << endl;system("pause");//vector<pair<string, string> > tickets2 = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]];return 0;}*/
思路:

算法非原创。原题解https://discuss.leetcode.com/topic/36370/short-ruby-python-java-c是leetcode上vote最多的解。主要原理是欧拉路径和DFS,这个我有想过,但对于分叉之间如何进行排列则想不出来,当分叉既有圈,又有非圈时,再加上字典数排序规则,情况变得很复杂。该算法中让最先访问的节点最后push_back,有点匪夷所思,但经过推敲发现确实可行,对于我设计的所有情况都能正确处理,我至今仍不能很清晰地描述这个方法的原理,大概明白的是, 一个节点下每条分支的叶子要么是节点本身,要么是题目的终点,而由于题目的保证,终点只有一个,所以利用这种push_back方式生成的一个分支的尾,就成了另一个分支的头。最后再将vector反转就行了。佩服第一个想出这个方法的人。

0 0