LeetCode332.重新安排行程
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/reconstruct-itinerary/
代码
class Solution:
def backtracking(self, tickets, used, cur, result, path):
if len(path) == len(tickets) + 1:
result.append(path[:])
return True
for i, ticket in enumerate(tickets):
if ticket[0] == cur and used[i] == 0:
used[i] = 1
path.append(ticket[1])
state = self.backtracking(tickets, used, ticket[1], result, path)
path.pop()
used[i] = 0
if state:
return True
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
tickets.sort()
used = [0] * len(tickets)
path = ['JFK']
result = []
self.backtracking(tickets, used, "JFK", result, path)
return result[0]