【陪伴式刷题】Day 26|回溯|332.重新安排行程(Reconstruct Itinerary)

刷题顺序按照代码随想录建议

题目描述

英文版描述

You are given a list of airline tickets where tickets[i] = [from(i), to(i)] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". 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"].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

Example 1:

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

Example 2:

Input: tickets = [["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.

Constraints:

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • from(i).length == 3
  • to(i).length == 3
  • from(i) and to(i) consist of uppercase English letters.
  • from(i) != to(i)

英文版地址

leetcode.com/problems/re...

中文版描述

给你一份航线列表 tickets ,其中 tickets[i] = [from(i), to(i)] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。

所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。

  • 例如,行程 ["JFK", "LGA"]["JFK", "LGB"] 相比就更小,排序更靠前。

假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。

示例 1:

输入: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] 输出: ["JFK","MUC","LHR","SFO","SJC"]

示例 2:

输入: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] 输出: ["JFK","ATL","JFK","SFO","ATL","SFO"] 解释: 另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。

提示:

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • from(i).length == 3
  • to(i).length == 3
  • from(i)to(i) 由大写英文字母组成
  • from(i) != to(i)

中文版地址

leetcode.cn/problems/re...

解题方法

递归法

Java 复制代码
class Solution {
    List<String> result = new ArrayList<>();
    Map<String, TreeMap<String, Integer>> map = new HashMap<>();

    public List<String> findItinerary(List<List<String>> tickets) {
        // 初始化map
        for (List<String> ticket : tickets) {
            String from = ticket.get(0);
            String end = ticket.get(1);
            map.putIfAbsent(from, new TreeMap<>());
            TreeMap<String, Integer> fromTreeMap = map.get(from);
            fromTreeMap.put(end, fromTreeMap.getOrDefault(end, 0) + 1);
        }
        result.add("JFK");
        boolean flag = backTrack(tickets, 0);
        return result;
    }

    private boolean backTrack(List<List<String>> tickets, int count) {
        if (result.size() == tickets.size() + 1) {
            return true;
        }
        String from = result.get(result.size() - 1);
        TreeMap<String, Integer> stringIntegerTreeMap = map.get(from);
        if(stringIntegerTreeMap == null){
            return false;
        }
        for (String ss : stringIntegerTreeMap.keySet()) {
            Integer mm = stringIntegerTreeMap.get(ss);
            if (mm > 0) {
                result.add(ss);
                map.get(from).put(ss, stringIntegerTreeMap.get(ss) - 1);
                boolean b = backTrack(tickets, count + 1);
                if (b) {
                    return true;
                }
                result.remove(result.size() - 1);
                map.get(from).put(ss, stringIntegerTreeMap.get(ss) + 1);
            }
        }
        return false;
    }
}

复杂度分析

  • 时间复杂度:不会啊不会啊= =// >> 回溯算法的时间复杂度,搞不懂啊(q求大神指点=[,,_,,]:3)
  • 空间复杂度:O(n),为递归过程中栈的开销,平均情况下为 O(log⁡n),最坏情况下树呈现链状,为 O(n)
相关推荐
py有趣4 分钟前
LeetCode学习之0矩阵
学习·leetcode·矩阵
在等晚安么9 分钟前
记录自己写项目的第三天,springbot+redis+rabbitma高并发项目
java·spring boot·redis·1024程序员节
OkGogooXSailboat33 分钟前
flume的log4j日志无输出排查
java·flume·1024程序员节
Q741_1471 小时前
C++ 分治 快速选择算法 堆排序 TopK问题 力扣 215. 数组中的第K个最大元素 题解 每日一题
c++·算法·leetcode·分治·1024程序员节·topk问题·快速选择算法
想睡好1 小时前
express中间件(java拦截器)
java·中间件·express
兢兢业业的小白鼠1 小时前
Java常用中间件整理讲解——Redis,RabbitMQ
java·中间件·java-rabbitmq·1024程序员节
鱼儿也有烦恼1 小时前
快速学完 LeetCode top 1~50 [特殊字符]
java·算法·leetcode·1024程序员节
独自破碎E1 小时前
LeetCode 380: O(1) 时间插入、删除和获取随机元素
java·算法·leetcode
信仰_2739932431 小时前
Mybatis一级缓存
java·缓存·mybatis
Brookty1 小时前
【算法】前缀和(二)使用
java·学习·算法·前缀和·动态规划·1024程序员节