给你一份航线列表tickets
,其中tickets[i] = [from_i, to_i]
表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从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 <= 300
tickets[i].length == 2
from_i.length == 3
to_i.length == 3
from_i
和to_i
由大写英文字母组成from_i != to_i
1.哈希+回溯
Python解答:
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
adic, bdic = {}, {}
for item in tickets:
if item[0] not in adic.keys():
adic[item[0]] = [item[1]]
else:
adic[item[0]].append(item[1])
if (item[0]+item[1]) not in bdic.keys():
bdic[item[0]+item[1]] = 1
else:
bdic[item[0]+item[1]] += 1
lens = len(tickets)
for key in adic.keys():
adic[key].sort()
result = None
def backtrace(orig, res, i):
nonlocal result
if i == lens:
result = copy.deepcopy(res)
return
else:
if orig in adic.keys():
dests = adic[orig]
for dest in dests:
if bdic[orig+dest] > 0:
bdic[orig+dest] -= 1
if not result:
backtrace(dest, res+[dest], i+1)
else:
return
bdic[orig+dest] += 1
backtrace('JFK', ['JFK'], 0)
return result
2.Hierholzer算法
Python解答:
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
adic = {}
for item in tickets:
if item[0] not in adic.keys():
adic[item[0]] = [item[1]]
else:
adic[item[0]].append(item[1])
for key in adic.keys():
adic[key].sort()
def dfs(node):
if node in adic.keys():
while adic[node]:
temp = adic[node].pop(0)
dfs(temp)
stack.append(node)
stack = []
dfs('JFK')
return stack[::-1]
留言