332. 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.
class Solution {
private final Deque<String> res = new LinkedList<>();
//map<出发机场, map<到达机场, 航班次数>> map
private final Map<String, Map<String, Integer>> map = new HashMap<>();
private boolean backTrack(int ticketNum) {
//长度
if (res.size() == ticketNum + 1) return true;
String last = res.getLast();
if (map.containsKey(last)) {
for (Map.Entry<String, Integer> target : map.get(last).entrySet()) {
int count = target.getValue();
if (count > 0) {
//增加元素并改值
res.add(target.getKey());
target.setValue(count - 1);
//递归
if (backTrack(ticketNum)) return true;
//回溯
res.removeLast();
target.setValue(count);
}
}
}
return false;
}
public List<String> findItinerary(List<List<String>> tickets) {
//先初始化所有的机票对应的map
for (List<String> ticket : tickets) {
Map<String, Integer> temp;
//如果有此出发机场
if (map.containsKey(ticket.get(0))) {
temp = map.get(ticket.get(0));
//给到达机场次数赋值:0或 +1 temp.put(ticket.get(1), temp.getOrDefault(ticket.get(1), 0) + 1);
} else {
//如果没有此出发机场,则创建新的map,并把第一个目标机场存进去
temp = new TreeMap<>();
temp.put(ticket.get(1), 1);
}
map.put(ticket.get(0), temp);
}
res.add("JFK");
backTrack(tickets.size());
return new ArrayList<>(res);
}
}