二分查找你学废了吗?快来看看这道题如何使用二分查找解决吧!
回溯算法练习题
LeetCode链接:162. 寻找峰值
1.题目描述
给你一份航线列表 tickets
,其中 $tickets[i] = [from_i, to_i]$ 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从 JFK
(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK
开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。
- 例如,行程
["JFK", "LGA"]
与 ["JFK", "LGB"]
相比就更小,排序更靠前。
假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。
示例 1:

1 2
| 输入:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] 输出:["JFK","MUC","LHR","SFO","SJC"]
|
示例 2:

1 2 3
| 输入:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] 输出:["JFK","ATL","JFK","SFO","ATL","SFO"] 解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。
|
提示:
- $1 <= tickets.length <= 300$
- $tickets[i].length == 2$
- $from_i.length == 3$
- $to_i.length == 3$
- $from_i$和 $to_i$ 由大写英文字母组成
- $from_i \ != to_i$
2.题解
2.1 回溯算法-写法1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| class Solution { public Deque<String> result = new LinkedList<>();
public Map<String, Map<String, Integer>> map = new HashMap<>();
public List<String> findItinerary(List<List<String>> tickets) { for (List<String> t : tickets) { Map<String, Integer> temp; if (map.containsKey(t.get(0))) { temp = map.get(t.get(0)); temp.put(t.get(1), temp.getOrDefault(t.get(1), 0) + 1); } else { temp = new TreeMap<>(); temp.put(t.get(1), 1); } map.put(t.get(0), temp); }
result.add("JFK");
backtracking(tickets.size());
return new ArrayList<>(result); }
public boolean backtracking(int ticketNum) { if (result.size() == ticketNum + 1) { return true; }
String last = result.getLast();
if (map.containsKey(last)) { for (Map.Entry<String, Integer> target : map.get(last).entrySet()) { int count = target.getValue(); if (count > 0) { result.add(target.getKey()); target.setValue(count - 1);
if (backtracking(ticketNum)) { return true; }
result.removeLast(); target.setValue(count); } } }
return false; } }
|
2.2 回溯算法-写法2-超时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| class Solution { private LinkedList<String> res; private LinkedList<String> path = new LinkedList<>();
public List<String> findItinerary(List<List<String>> tickets) { Collections.sort(tickets, (a, b) -> a.get(1).compareTo(b.get(1)));
path.add("JFK");
boolean[] used = new boolean[tickets.size()];
backTracking((ArrayList) tickets, used);
return res; }
public boolean backTracking(ArrayList<List<String>> tickets, boolean[] used) { if (path.size() == tickets.size() + 1) { res = new LinkedList<>(path); return true; }
for (int i = 0; i < tickets.size(); i++) { if (!used[i] && tickets.get(i).get(0).equals(path.getLast())) { path.add(tickets.get(i).get(1)); used[i] = true;
if (backTracking(tickets, used)) { return true; }
used[i] = false; path.removeLast(); } }
return false; } }
|