LeetCode(力扣)332.重新安排行程Python

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]

猜你喜欢

转载自blog.csdn.net/qq_44953660/article/details/132783033