332. Reconstruct Itinerary


"""
        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]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这题做了一天。。一天。。上午拿到之后感觉挺easy的,我想像NQueens那样先DFS找到所有的解。结果怎么也无法...
    DrunkPian0阅读 1,521评论 0 0
  • 把每个机场视为一个节点,一张机票视为连接两个机场节点的有向边,这道题实际上是求一个有向图的一笔画问题,即从一个确定...
    MarchingCoder阅读 5,801评论 0 0
  • Given a list of airline tickets represented by pairs of d...
    matrxyz阅读 4,266评论 0 0
  • 0x01 PoC PoC(全称: Proof of Concept), 又叫概念验证。作为我们的漏洞验证程序,他可...
    Hell0_C阅读 13,988评论 4 14
  • 第十周【周检视】 不知不觉竟然已经第十周了 【收获】1、每天打卡7/7 2、每天自拍 6/7 其他一些零零碎碎的东...
    tracy_bacb阅读 761评论 0 0