LeetCode 332. Reconstruct Itinerary 解答

2019/02/03 难度 Medium 主题

视频讲解

代码

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        g = collections.defaultdict(dict)
        for u,v in tickets:
            if v not in g[u]:
                g[u][v] = 0
            g[u][v] += 1
        print(g)
        
        
        res = None
        def dfs(g, curr, path):
            
            nonlocal res
            
            if res :
                return
            
            if len(path) == len(tickets) + 1:
                res = path[:]
            
            for neighbor in sorted(g[curr].keys()):
                
                if g[curr][neighbor] == 0:
                    continue
                
                g[curr][neighbor]-=1
                path.append(neighbor)
                
                dfs(g, curr = neighbor, path = path)
                
                g[curr][neighbor] += 1
                path.pop()
            
        dfs(g, "JFK", ['JFK'])
        return res

PPT讲解

本题涉及的知识点:

  • [()][]

我的 Leetcode 讲解频道

代码链接

面试高频考点Youtube链接

面试低频考点Youtube链接

站内搜索 | Search


    视频 | Video Links

    Table of Contents