leetcode reconstruct-itinerary
来源:互联网 发布:数控铣好看编程图案 编辑:程序博客网 时间:2024/06/03 07:21
题目链接
这个题目虽然是用的深度优先算法。其实并不是经典的深度优先。首先这个题的深度优先遍历有顺序。必须是字典序从小到大的。所以用了sortedMap这个数据结构。其次。深度优先遍历如果一个点已经使用过,那么这个点第二次遍历就不能再使用。不过这里是可以在使用的。所以就需要使用每个边进行标记。如果这个边已经使用那就不能在使用,所以便有了这个数据结构sortedMap
import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.PriorityQueue;import java.util.Set;import java.util.SortedMap;import java.util.TreeMap;public class Solution { public static void main(String args[]) { Solution solution=new Solution(); solution.findItinerary(new String [][]{{"MUC","LHR"},{"JFK","MUC"},{"SFO","SJC"},{"LHR","SFO"}}); } HashMap<String, SortedMap<String,Integer>> map=new HashMap<String, SortedMap<String,Integer>>(); LinkedList<String> result=new LinkedList<String>(); int n; public List<String> findItinerary(String[][] tickets) { n=tickets.length; for(int i=0;i<tickets.length;i++) { SortedMap<String,Integer> theGet=map.get(tickets[i][0]); if(theGet==null) { theGet=new TreeMap<String,Integer>(); map.put(tickets[i][0], theGet); } Integer count=theGet.get(tickets[i][1]); if(count==null) { theGet.put(tickets[i][1], 1); } else { theGet.put(tickets[i][1],count+1); } } String current="JFK"; result.add(current); help(current); return result; } boolean help(String current) { if(result.size()==n+1) { return true; } SortedMap<String,Integer> theGet=map.get(current); if(theGet!=null) { Set<String> keys = theGet.keySet(); for (String key : keys){ if(theGet.get(key)!=0) { theGet.put(key, theGet.get(key)-1); result.add(key); if(help(key))return true; result.pollLast(); theGet.put(key, theGet.get(key)+1); } } } return false; }}
0 0
- leetcode Reconstruct Itinerary
- *[LeetCode]332. Reconstruct Itinerary
- leetcode 332. Reconstruct Itinerary
- [LeetCode 332] Reconstruct Itinerary
- LeetCode 332 : Reconstruct Itinerary
- leetcode笔记:Reconstruct Itinerary
- LeetCode *** 332. Reconstruct Itinerary
- leetcode reconstruct-itinerary
- LeetCode 332. Reconstruct Itinerary
- 【Leetcode】Reconstruct Itinerary
- LeetCode No332. Reconstruct Itinerary
- leetcode 332 Reconstruct Itinerary
- leetcode 332. Reconstruct Itinerary
- LeetCode[332] Reconstruct Itinerary
- [leetcode] 332. Reconstruct Itinerary
- Leetcode 332. Reconstruct Itinerary
- Leetcode 332. Reconstruct Itinerary
- [LeetCode] Reconstruct Itinerary
- CODEFORCE 672 题解(ABC)
- 身边的素质教育
- HDU 3849 By Recognizing These Guys, We Find Social Networks Useful 边双连通
- Java三大布局介绍
- 基因治疗抗衰老首获成功:减轻肌肉质量及干细胞损耗
- leetcode reconstruct-itinerary
- Bootstrap3 多个模态对话框无法显示的问题
- I00013 鸡兔同笼
- Fresco 专为ANDROID加载图片(简单使用)
- 树形dp
- 238. Product of Array Except Self
- maven 发布项目到tomcat
- java command 编译 打包
- windows xp vc 6.0编译最新net-snmp源码