Leetcode 刷题 - 332 - Reconstruct Itinerary

Python interview - override & overload 我们先说overload 重载。 在Java中,支持重载,重载的意思是能够定义有相同方法名的方法,传入方法中的参数个数,或者参数类型不同。比如: int mymethod(int a, int b) int mymethod(int num) float mymethod(int a, float b) float mymethod(float var1, int var2) in 阅读详情

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值对。



Arch Linux双系统安装避坑指南:从Windows分区到桌面环境全流程 本文提供了一份详尽的Arch Linux与Windows双系统安装避坑指南。内容涵盖从安装前的UEFI环境确认、BitLocker处理、分区规划,到Live环境进入、基础系统安装、GRUB引导配置,再到显卡驱动安装、KDE/GNOME桌面环境部署及中文化设置的全流程。重点解决了双系统安装中的核心痛点,帮助用户在不破坏现有Windows系统的前提下,顺利完成Arch Linux的安装。 阅读详情

相关推荐

2024美团秋招硬件开发笔试真及答案解析

在 Linux 内核的网络设备驱动中,数据链路层的功能通常由网络协议栈的低层(如以太网驱动)实现,而不是作为网络设备驱动的一个独立层次。在 FreeRTOS 中,任务通知(Task Notifications)是一种轻量级的事件传递机制,用于在任务之间或任务与中断之间传递信号。小美正在开发一个简单的密码生成器,其中一个功能是将输入的字符串中的所有字母按字母顺序循环前移一位(即 'a' 变为 'z','B' 变为 'A',以此类推)。它包含了网络设备的各种参数和方法,用于管理网络设备的初始化、配置和操作。

XU157303764的博客 1578

leetcode 332 Reconstruct Itinerary

Reconstruct Itinerary

GadyPu的专栏 637

鱼鹰优化算法(OOA)详解:从猛禽捕食智能到优化算法实现

鱼鹰优化算法(Osprey Optimization Algorithm, OOA)是2023年提出的一种新型元启发式优化算法,灵感来源于鱼鹰(一种中型猛禽)高效的捕食策略。算法模拟了鱼鹰从空中识别水下鱼类位置并俯冲捕食,然后将捕获的鱼带至安全位置享用的全过程,以此抽象出全局探索和局部开发两个核心阶段。OOA算法具有参数少、结构简单、收敛速度快、全局寻优能力强等特点。自提出以来,已在函数优化、机器学习参数调优(如CatBoost模型)、路径规划等多个领域展现出良好性能,为解决复杂优化问提供了新的有效工具。

qq_42212808的博客 255

Leetcode 332. Reconstruct Itinerary

Leetcode 332. Reconstruct Itinerary dfs:   熟悉深度优先搜索的代码结构,回溯+递归 import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.ut

独钓寒江雪 576

[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

coder 进阶的专栏 2868

LeetCode //C - 332. Reconstruct Itinerary

【代码】LeetCode //C - 332. Reconstruct Itinerary

Made in Code 828

Leetcode: 332.Reconstruct Itinerary

Leetcode: 332.Reconstruct Itinerary

qq_16318319的博客 486

leetcode 332. Reconstruct Itinerary | 332. 重新安排行程(Java)

目 https://leetcode.com/problems/reconstruct-itinerary/ 解 要把 next 数组按照字典序排列,所以用了 sorted 集合。两个坑: 必须从 JFK 开始 同一个路线会重复出现 最朴素的思路 DFS,还好没超时。分析过程见下图~ 后来根据测试用例发现路线会重复。。 import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; class Vertex {

寒泉 5万+

[leetcode] 332. Reconstruct Itinerary报告

目链接:https://leetcode.com/problems/reconstruct-itinerary/ Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order.

小榕流光的专栏 6049

LeetCode: 332. Reconstruct Itinerary

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 belo...

杨领well的专栏 350

[leetcode] 332. Reconstruct Itinerary @ python

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,...

闲庭信步 561

Leetcode - 325 - Maximum Size Subarray Sum Equals k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead. Example 1: Given nums = [1, -1, 5, -2, 3], k = 3, return 

2167

Python challenge 9 - bz2

第九地址:http://www.pythonchallenge.com/pc/def/integrity.html 依旧是图片,我们点击一下会弹出用户名,密码让我们输入,猜测解析之后会得到。继续查看HTML代码。 <!-- un: 'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x

1323

Python challenge 7 - zipfile

第七地址:http://www.pythonchallenge.com/pc/def/channel.html 根据提示,我们看到,试一试之后发现可以把channel.html改成channel.zip,然后下载得到一个zip文件。 打开zip文件,其中的readme.txt,我们得到如下的提示 welcome to my zipped list. hint1: star

1147

Leetcode - 296 - Best Meeting Point

A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calcu

988

Python interview - text to JSON & zip & with statement

自己写的小例子,就是把本地的txt文件转换为JSON格式输出。 data source 简单的1-10存一个文件, A-J 存一个文件 import json book = 'C:\Python27\\book.txt' date = 'C:\Python27\date.txt' book_list = [] date_list = [] with open(book)

888

Leetcode - 323 - Number of Connected Components in an Undirected Graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. Example 1:

882

Python interview - Marshal & JSON & Pickle

Python中有很多模块提供了序列化与反序列化的功能,比如marshal,pickle,cPickle。可以在需要的时候把对象持久化保存到磁盘上,或者序列化成二进制流通过网络发送到远程主机上。 If you’re serializing and de-serializing Python objects, use the pickle module instead – the perform

799

Python interview - ternary conditional operator 三目运算符

三目运算符,是c语言的重要组成部分。条件运算符是唯一有三个操作数的运算符,又称为三元运算符。 在c语言风格的语言中,三元操作符的形式如下: ? : 但是在python中并没有这样的操作符,在python 2.5之前,可以用如下的方式表示三元运算符 (X, Y)[C] 其中C为条件,如果C不成立,那么元祖中的第一个元素X被返回,如果C成立,那么返回第二个元素Y。 

699

Python challenge 3 - urllib & re

第三的地址:http://www.pythonchallenge.com/pc/def/ocr.html Hint1:recognize the characters. maybe they are in the book, but MAYBE they are in the page source. Hint2: 网页源码的注释中有: find rare characters in t

657

2025海南省河流水系矢量图层shp数据-水系线水系面数据下载

2025海南省河流水系矢量图层shp数据下载-包含水系线和水系面数据,几千上万条数据,非常细化,坐标系为WGS1984坐标系统

DM检验 matlab 软件

模型比较时 运动DM检验进行检验

上一篇: Leetcode 刷题 - 323 - Number of Connected Components in an Undirected Graph
加藤蜀黍
博客等级 码龄17年 7粉丝 86原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值