国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

[LeetCode] Reconstruct Itinerary

2019-11-09 16:22:29
字體:
供稿:網(wǎng)友

題目

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: 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. Example 1: tickets = [[“MUC”, “LHR”], [“JFK”, “MUC”], [“SFO”, “SJC”], [“LHR”, “SFO”]] Return [“JFK”, “MUC”, “LHR”, “SFO”, “SJC”].

解題

題目大意是找一條路徑,可以從頭到尾的羅列出每個航站。其實就是一個有向圖,然后一筆畫畫完所有的點,按順序列出所有的點。也就是歐拉路徑的定義。 首先題目定義,必然存在一條歐拉路徑,且每個點有多個路徑按字典序排序。首先采用dfs尋找字典序最小的一條路徑,直到某點阻塞,不能通往新的點,那么這一點必然是歐拉路徑的終點。也就得到了一條從起點到終點的路徑L。 對于路徑中的其它點,只能和路徑組成環(huán),在dfs遞歸回退的過程中,每一點繼續(xù)dfs遍歷,最終會阻塞在L上,并組成一個環(huán),回退該路徑并記錄即可。相當于在每個點尋找到L的路徑,并將其并回L。同時遞推回歸的過程中,先回歸的點在路徑的后面,所以要逆著記錄進鏈表。

public class Solution { LinkedList<String> res; Map<String,PriorityQueue<String>> edges; public List<String> findItinerary(String[][] tickets) { edges = new HashMap<>(); res = new LinkedList<>(); for (String[] ticket : tickets) { if (!edges.containsKey(ticket[0])){ PriorityQueue<String> queue = new PriorityQueue<>(); queue.add(ticket[1]); edges.put(ticket[0], queue); }else { edges.get(ticket[0]).add(ticket[1]); } } dfs("JFK"); return res; } private void dfs(String cur) { while (edges.containsKey(cur) && !edges.get(cur).isEmpty()) { dfs(edges.get(cur).poll()); } res.add(0,cur); }}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 汉沽区| 阿巴嘎旗| 句容市| 贵定县| 区。| 遵义市| 大关县| 都匀市| 阜宁县| 延安市| 醴陵市| 阿拉善左旗| 龙泉市| 蓬莱市| 乐昌市| 江口县| 香格里拉县| 湄潭县| 桃源县| 太湖县| 津南区| 汝南县| 和顺县| 临夏市| 开江县| 紫云| 郎溪县| 威远县| 延寿县| 汨罗市| 留坝县| 武鸣县| 大邑县| 陵水| 崇礼县| 温宿县| 平塘县| 托克逊县| 洪雅县| 子长县| 抚顺县|