美文网首页
332. Reconstruct Itinerary

332. Reconstruct Itinerary

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-13 14:48 被阅读0次

"""
        key is to store tickets information in default dictionary in lexical order.
        and what to do when ran into destination before going through all tickets. 
        if encounter destination, add to result list first. 
        then reverse the result in the end. 
        """
iterative solution 

class Solution(object):
    def findItinerary(self, tickets):
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        targets=collections.defaultdict(list)
        for a , b in sorted(tickets)[::-1]:
            targets[a]+=[b]
        #print targets
        route =[]
        stack=['JFK']
        while stack:
            while targets[stack[-1]]:
                stack.append(targets[stack[-1]].pop())
            route.append(stack.pop())
        return route[::-1]


recursive solution 
class Solution(object):
    def findItinerary(self, tickets):
        """
        :type tickets: List[List[str]]
        :rtype: List[str]
        """
        targets=collections.defaultdict(list)
        for a , b in sorted(tickets)[::-1]:
            targets[a]+=[b]
        #print targets
        route =[]
        def visit(airport):
            
            while targets[airport]:
                visit(targets[airport].pop())
            route.append(airport)
        visit('JFK')
        return route[::-1]

相关文章

网友评论

      本文标题:332. Reconstruct Itinerary

      本文链接:https://www.haomeiwen.com/subject/phqbmttx.html