• 【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:

    Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
    Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]
    

    Example 2:

    Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
    Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
    Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
                 But it is larger in lexical order.

    解题思路:本题是非常典型的欧拉回路的场景,但有两点需要注意的,一是要求返回结果是最小字典序,所有事先需要对所有机场先按升序排好;第二点有点坑,欧拉回路一条边只能走一次,但本题中输入的tickets中,起点和终点相同的ticket可能有多个。

    代码如下:

    class Solution(object):
        res = []
        def euler(self,airports,board,portlist):
            for i in range(len(board[airports])):
                if board[airports][i] > 0 :
                    board[airports][i] -= 1
                    self.euler(i,board,portlist)
            self.res.insert(0,portlist[airports])
    
    
        def findItinerary(self, tickets):
            """
            :type tickets: List[List[str]]
            :rtype: List[str]
            """
            #print len(tickets)
            self.res = []
            inx = 0
            dic = {}
            for (v1,v2) in tickets:
                if v1 not in dic:
                    dic[v1] = 1
                if v2 not in dic:
                    dic[v2] = inx
    
            portlist = dic.keys()
            portlist.sort()
    
            board = []
            dic = {}
            for i in range(len(portlist)):
                board.append([0]*len(portlist))
                dic[portlist[i]] = i
    
            for (v1, v2) in tickets:
                board[dic[v1]][dic[v2]] += 1
                
            self.euler(dic['JFK'],board,portlist)
            return self.res
  • 相关阅读:
    Samba网络配置
    嵌入式汇编程序
    GDB常用命令
    Everything搜索结果显示0 Object
    关于值类型和引用类型
    Main()

    利用python脚本自动下载ICML会议接受的文章
    如何从mac下的photos导出照片
    Erlang语言研究综述
  • 原文地址:https://www.cnblogs.com/seyjs/p/10107050.html
Copyright © 2020-2023  润新知