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