Leetcode 刷题 - 332 - Reconstruct Itinerary

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Note:

  1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets form at least one valid itinerary.

Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].

Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.



根据题意,input是一系列换乘的机票,肯定有一种方式可以连接起来。要求从JFK出发,把所有的机场按照顺序排序,同时,如果有选择,机场的顺序需要按照字母顺序排列。

1. 采用字典,departure - [ arrival ]

2. dfs 深度搜索,递归调用

3. trace back 回溯,增加判断如果不可能的就恢复数据,然后返回继续dfs搜索


class Solution(object):
    def findItinerary(self, tickets):
        result = ["JFK"]

        dic = collections.defaultdict(list) # defaultdict never raise KeyError
        for flight in tickets:
            dic[flight[0]] += flight[1],

        self.dfs_helper(dic, "JFK", result, len(tickets))

        return result

    def dfs_helper(self, dic, departure, result, flights):
        if len(result) == flights + 1: # dfs出口,条件成立表示找到了最终的结果
            return result

        currentDst = sorted(dic[departure]) 
        for dst in currentDst: # loop所有的目的地
            dic[departure].remove(dst)
            result.append(dst)

            valid = self.dfs_helper(dic, dst, result, flights) # 深度搜索,对每个目的地进行loop
            if valid: # 递归得到dfs的值。如果当前dst没有目的地,会返回None
                return valid

            result.pop() # 回复步骤。如果返回的是None,就把result和字典复原,数据复原后继续下一个搜索
            dic[departure].append(dst)


=======

collections.defaultdict()

defaultdict()永远不会出现KeyError的错误。


from collections import defaultdict

def default_function():
    return 'default value'

ice_cream = defaultdict(default_function, Hello='World')
ice_cream['Sarah'] = 'Chunky Monkey'
ice_cream['Abdul'] = 'Butter Pecan'
print ice_cream['Sarah']
# Chunky Monkey
print ice_cream['Joe']
# Vanilla
print ice_cream['Hello']


如果没有Key在字典中,会自动输出Default Function的值。我们也可以直接在生成字典的时候直接定义一些key-value值对。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值