LeetCode 题解工作台
重新安排行程
给你一份航线列表 tickets ,其中 tickets[i] = [from i , to i ] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。 所有这些机票都属于一个从 JFK (肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返…
3
题型
5
代码语言
3
相关题
当前训练重点
困难 · 图·DFS·traversal
答案摘要
题目实际上是给定 个点和 条边,要求从指定的起点出发,经过所有的边恰好一次,使得路径字典序最小。这是一个典型的欧拉路径问题。 由于本题保证了至少存在一种合理的行程,因此,我们直接利用 Hierholzer 算法,输出从起点出发的欧拉路径即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路
题目描述
给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。
- 例如,行程
["JFK", "LGA"]与["JFK", "LGB"]相比就更小,排序更靠前。
假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。
示例 1:
输入:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] 输出:["JFK","MUC","LHR","SFO","SJC"]
示例 2:
输入:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] 输出:["JFK","ATL","JFK","SFO","ATL","SFO"] 解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。
提示:
1 <= tickets.length <= 300tickets[i].length == 2fromi.length == 3toi.length == 3fromi和toi由大写英文字母组成fromi != toi
解题思路
方法一:欧拉路径
题目实际上是给定 个点和 条边,要求从指定的起点出发,经过所有的边恰好一次,使得路径字典序最小。这是一个典型的欧拉路径问题。
由于本题保证了至少存在一种合理的行程,因此,我们直接利用 Hierholzer 算法,输出从起点出发的欧拉路径即可。
时间复杂度 ,空间复杂度 。其中 是边的数量。
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
def dfs(f: str):
while g[f]:
dfs(g[f].pop())
ans.append(f)
g = defaultdict(list)
for f, t in sorted(tickets, reverse=True):
g[f].append(t)
ans = []
dfs("JFK")
return ans[::-1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(E log E) due to sorting adjacency lists, and space complexity is O(V + E) for the graph and recursive call stack, where V is airports and E is tickets. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate identifies graph representation with adjacency lists.
- question_mark
Candidate sorts destinations to handle lexical order correctly.
- question_mark
Candidate uses DFS and recognizes Eulerian path formation with backtracking.
常见陷阱
外企场景- error
Failing to sort adjacency lists leading to incorrect lexical order.
- error
Not removing edges after visiting, causing repeated use of the same ticket.
- error
Appending instead of prepending during backtracking, yielding reversed itinerary.
进阶变体
外企场景- arrow_right_alt
Allowing multiple starting airports instead of fixed 'JFK'.
- arrow_right_alt
Returning all possible valid itineraries instead of just the smallest lexical order.
- arrow_right_alt
Using BFS instead of DFS for traversal with priority queue for lexical order.