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.
解法1:建图 + DFS
首先是建图的思想,这题看起来就要用DFS,可是没有图可以操作,对于这类的问题要想到用一个Hashmap来构造图的边的关系。
这里有一个小的trick是用到了PriorityQueue, 因为最后的结果是要排序后较小的,那么我们构建hashmap的时候就要把每一个start对应的destination排好序,我们就可以用PQ来存储。
而题目有一个隐含的条件就是一定有解,那么如果我们在搜索碰到一个没有对应destination的城市的时候,他一定是要求的最后一个string。
所以我们在写DFS的时候,要把res.add(cur)放在while语句之后。
Java