LeetCode-332. Reconstruct Itinerary [C++][Java]

本文解析了LeetCode题目332,介绍了如何根据给定的航班票务信息,按最小字典序重构旅行路线。涉及C++和Java解决方案,展示了使用栈和深度优先搜索(DFS)的方法。

LeetCode-332. Reconstruct Itineraryhttps://leetcode.com/problems/reconstruct-itinerary/

You are given a list of airline tickets where tickets[i] = [fromi, toi] 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
  • fromi.length == 3
  • toi.length == 3
  • fromi and toi consist of uppercase English letters.
  • fromi != toi

【C++】

1.Reconstruct Itinerary

class Solution {
public:
    vector<string> findItinerary(vector<vector<string>>& tickets) {
        vector<string> ans;
        if (tickets.empty()) {return ans;}
        unordered_map<string, multiset<string>> hash;
        for (const auto & ticket: tickets) {
            hash[ticket[0]].insert(ticket[1]);
        }
        stack<string> s;
        s.push("JFK");
        while (!s.empty()) {
            string next = s.top();
            if (hash[next].empty()) {
                ans.push_back(next);
                s.pop();
            } else {
                s.push(*hash[next].begin());
                hash[next].erase(hash[next].begin());
            }
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

2. DFS without stack

class Solution {
    unordered_map<string, multiset<string>> adj;
    void dfs(vector<string> &ans, string src) {
        while (!adj[src].empty()) {
            string dst = *adj[src].begin();
            adj[src].erase(adj[src].begin());
            dfs(ans, dst);
        }
        ans.push_back(src);
    }
public:
    vector<string> findItinerary(vector<vector<string>>& tickets) {
        vector<string> ans;
        if (tickets.empty()) {return ans;}
        for (int i = 0; i < tickets.size(); i++) {adj[tickets[i][0]].insert(tickets[i][1]);}
        dfs(ans, "JFK");
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

【Java】

class Solution {
    Map<String, PriorityQueue<String>> map =  new HashMap<>();
    void dfs(List<String> result, String start){
        PriorityQueue<String> qu = map.getOrDefault(start, new PriorityQueue<>());
        while (!qu.isEmpty()) {dfs(result, qu.remove());}
        result.add(start);
    }
    public List<String> findItinerary(List<List<String>> tickets) {
        List<String> result = new ArrayList<>();
        for(List<String> ticket : tickets){
            map.putIfAbsent(ticket.get(0), new PriorityQueue<String>());
            map.get(ticket.get(0)).add(ticket.get(1));
        }
        dfs(result, "JFK");
        Collections.reverse(result);
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值