mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Merge pull request #2410 from davidgao7/master
修改:0322.重新安排行程.md 解决python代码块 回溯使用字典方法代码超时问题
This commit is contained in:
@ -449,34 +449,37 @@ class Solution:
|
||||
```
|
||||
回溯 使用字典
|
||||
```python
|
||||
from collections import defaultdict
|
||||
|
||||
class Solution:
|
||||
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
|
||||
targets = defaultdict(list) # 构建机场字典
|
||||
for ticket in tickets:
|
||||
targets[ticket[0]].append(ticket[1])
|
||||
for airport in targets:
|
||||
targets[airport].sort() # 对目的地列表进行排序
|
||||
self.adj = {}
|
||||
|
||||
path = ["JFK"] # 起始机场为"JFK"
|
||||
self.backtracking(targets, path, len(tickets))
|
||||
return path
|
||||
# sort by the destination alphabetically
|
||||
# 根据航班每一站的重点字母顺序排序
|
||||
tickets.sort(key=lambda x:x[1])
|
||||
|
||||
def backtracking(self, targets, path, ticketNum):
|
||||
if len(path) == ticketNum + 1:
|
||||
return True # 找到有效行程
|
||||
# get all possible connection for each destination
|
||||
# 罗列每一站的下一个可选项
|
||||
for u,v in tickets:
|
||||
if u in self.adj: self.adj[u].append(v)
|
||||
else: self.adj[u] = [v]
|
||||
|
||||
airport = path[-1] # 当前机场
|
||||
destinations = targets[airport] # 当前机场可以到达的目的地列表
|
||||
for i, dest in enumerate(destinations):
|
||||
targets[airport].pop(i) # 标记已使用的机票
|
||||
path.append(dest) # 添加目的地到路径
|
||||
if self.backtracking(targets, path, ticketNum):
|
||||
return True # 找到有效行程
|
||||
targets[airport].insert(i, dest) # 回溯,恢复机票
|
||||
path.pop() # 移除目的地
|
||||
return False # 没有找到有效行程
|
||||
# 从JFK出发
|
||||
self.result = []
|
||||
self.dfs("JFK") # start with JFK
|
||||
|
||||
return self.result[::-1] # reverse to get the result
|
||||
|
||||
def dfs(self, s):
|
||||
# if depart city has flight and the flight can go to another city
|
||||
while s in self.adj and len(self.adj[s]) > 0:
|
||||
# 找到s能到哪里,选能到的第一个机场
|
||||
v = self.adj[s][0] # we go to the 1 choice of the city
|
||||
# 在之后的可选项机场中去掉这个机场
|
||||
self.adj[s].pop(0) # get rid of this choice since we used it
|
||||
# 从当前的新出发点开始
|
||||
self.dfs(v) # we start from the new airport
|
||||
|
||||
self.result.append(s) # after append, it will back track to last node, thus the result list is in reversed order
|
||||
|
||||
```
|
||||
回溯 使用字典 逆序
|
||||
|
Reference in New Issue
Block a user