Reconstruct Itinerary
https://leetcode.com/problems/reconstruct-itinerary/description/
Last updated
Was this helpful?
https://leetcode.com/problems/reconstruct-itinerary/description/
Last updated
Was this helpful?
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.
要求从固定一个点开始,把所有边都走一次且要求路径上排在前面的结点权值尽量小,给定这样的路径一定存在。 欧拉路径,也叫做"一笔画"问题。最直接的思路是从root从权值小的点开始DFS,如果走不通就回溯到另一个子节点。因为这道题要求每个边都走一遍且给定欧拉路径一定存在,也就是说走不通意味着另一边一定能走通:把无向图看成树,右子树最后一个结点能形成环从而回到当前结点并再走一遍左子树以满足欧拉路径一定存在。当左子树可以走通并也形成蹦回root的环时,root和右子树直接看作左子树后面的子树。此时发现通过后序遍历并把遍历过的子节点删除,最后再反转所有结果,能对这两种情况都给出正确解。注意这里的后序遍历不能直接套用以前在二叉树上的iterative后序遍历,原因如图所示:
左边是生产的edge list表示出的节点关系,按照一般后序遍历会得到1231,而想得到的顺序是后序遍历右图得到的3121(=r>1213)。
每天边遍历一次O(N).