[LeetCode] 332. Reconstruct Itinerary

本文介绍了一种解决行程重建问题的方法,即根据一系列机票信息重构旅行路线。重点在于如何使用哈希表进行字典序DFS搜索来确保正确且高效地构建行程路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

注意

  • 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”].
  • All airports are represented by three capital letters (IATA code).
  • You may assume all tickets form at least one valid itinerary.

分析

开始的想法就是在数组中寻找符合from的to中最小的加入数组中,但是发现有个测例是不通过的,在该测例中这样找无法找到后续的to。

class Solution {
public:
  vector<string> findItinerary(vector<pair<string, string>> tickets) {
    const int n = tickets.size();
    vector<string> result;
    result.push_back("JFK");
    int visited[n];
    int i, j, pos, size = tickets.size(), count = 0;
    string from = "JFK", to;
    for (i = 0; i < size; i++) {
      visited[i] = 0;
    }
    while (count != size) {
      to = "";
      for (j = 0; j < size; j++) {
        if (visited[j]) continue;
        if (get<0>(tickets[j]) == from) {
          if (to == "") {
            to = get<1>(tickets[j]);
            pos = j;
          } else {
            if (to > get<1>(tickets[j])) {
              to = get<1>(tickets[j]);
              pos = j;
            }
          }
        }
      }
      count++;
      visited[pos] = 1;
      from = to;
      result.push_back(to);
    }
    return result;
  }
};

后来从上网查找思路,找到一个思路是建立一个以from为key的哈希表,然后按照字典序进行DFS查找,相同字典序则从小到大进行选择,直到某处没有可以相连的to那么就找到了想要的路径,这样才把结果依次加入数组,这样数组的信息是反向的,之后对这个路径进行反向输出就可以了。

代码

class Solution {
public:
  void DFS(string from) {
    while (hashTable[from].size() > 0) {
      string to = *hashTable[from].begin();
      hashTable[from].erase(hashTable[from].begin());
      DFS(to);
    }
    result.push_back(from);
  }
  vector<string> findItinerary(vector<pair<string, string>> tickets) {
    if(tickets.size() == 0) return {};
    for (auto val : tickets) {
      hashTable[val.first].insert(val.second);
    }
    DFS("JFK");
    reverse(result.begin(), result.end());
    return result;
  }
private:
  vector<string> result;
  unordered_map<string, multiset<string>> hashTable;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值