zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    spring mvc中的@PathVariable
    JSP禁用缓存的方式 response.setHeader( "Pragma", "no-cache" ); setDateHeader("Expires", 0);
    request.getSession(true)和request.getSession(false)的区别
    Spring Mvc中DispatcherServlet和Servlet的区别小结
    web.xml中load-on-startup的作用
    Spring MVC过滤器-字符集过滤器(CharacterEncodingFilter)
    web.xml配置中的log4jRefreshInterval
    web.xml中webAppRootKey
    关于tolua的使用
    关于#pragma pack
  • 原文地址:https://www.cnblogs.com/seyjs/p/10107050.html
Copyright © 2011-2022 走看看