日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

leetcode 332. Reconstruct Itinerary | 332. 重新安排行程(Java)

發布時間:2024/2/28 java 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 332. Reconstruct Itinerary | 332. 重新安排行程(Java) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

https://leetcode.com/problems/reconstruct-itinerary/

題解

要把 next 數組按照字典序排列,所以用了 sorted 集合。兩個坑:

  • 必須從 JFK 開始
  • 同一個路線會重復出現

最樸素的思路 DFS,還好沒超時。分析過程見下圖~

后來根據測試用例發現路線會重復。。

import java.util.*; import java.util.concurrent.ConcurrentSkipListMap;class Vertex {String val;SortedMap<String, Integer> next;public Vertex(String val) {this.val = val;this.next = new ConcurrentSkipListMap<>();}public void incr(String next) {Integer count = this.next.get(next);if (count == null) this.next.put(next, 1);else this.next.put(next, count + 1);}public void decr(String next) {int count = this.next.get(next) - 1;if (count == 0) this.next.remove(next);else this.next.put(next, count);} }class Solution {int size;public List<String> findItinerary(List<List<String>> tickets) {size = tickets.size();Map<String, Vertex> graph = new HashMap<>();for (List<String> ticket : tickets) {graph.putIfAbsent(ticket.get(0), new Vertex(ticket.get(0)));graph.putIfAbsent(ticket.get(1), new Vertex(ticket.get(1)));graph.get(ticket.get(0)).incr(ticket.get(1));}// dfs 并關注出度Stack<String> stack = new Stack<>();tryDFS(graph, "JFK", stack);System.out.println(stack);return stack;}public boolean tryDFS(Map<String, Vertex> graph, String from, Stack<String> stack) {stack.push(from);System.out.println(graph.get(from).next);if (graph.get(from).next.isEmpty()) {if (stack.size() == size + 1) {return true;} else {stack.pop();return false;}}for (String next : graph.get(from).next.keySet()) { // 只要有一條可行路徑 就返回graph.get(from).decr(next);if (tryDFS(graph, next, stack)) return true; // 此路可行else graph.get(from).incr(next); // 此路不可行}// 沒有遇到可行路徑stack.pop();return false;} }

總結

以上是生活随笔為你收集整理的leetcode 332. Reconstruct Itinerary | 332. 重新安排行程(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。