leetcode 332题
老师你好,leetcode 332题有一个解法
Approach 1: Backtracking + Greedy
它都答案我看明白了,但是它的时间复杂度和空间复杂度我都没看明白,你这边可以帮我理解它的这个时间复杂度吗 :)
它的解法:
相关代码:
class Solution {
// origin -> list of destinations
HashMap<String, List<String>> flightMap = new HashMap<>();
HashMap<String, boolean[]> visitBitmap = new HashMap<>();
int flights = 0;
List<String> result = null;
public List<String> findItinerary(List<List<String>> tickets) {
// Step 1). build the graph first
for (List<String> ticket : tickets) {
String origin = ticket.get(0);
String dest = ticket.get(1);
if (this.flightMap.containsKey(origin)) {
List<String> destList = this.flightMap.get(origin);
destList.add(dest);
} else {
List<String> destList = new LinkedList<String>();
destList.add(dest);
this.flightMap.put(origin, destList);
}
}
// Step 2). order the destinations and init the visit bitmap
for (Map.Entry<String, List<String>> entry : this.flightMap.entrySet()) {
Collections.sort(entry.getValue());
this.visitBitmap.put(entry.getKey(), new boolean[entry.getValue().size()]);
}
this.flights = tickets.size();
LinkedList<String> route = new LinkedList<String>();
route.add("JFK");
// Step 3). backtracking
this.backtracking("JFK", route);
return this.result;
}
protected boolean backtracking(String origin, LinkedList<String> route) {
if (route.size() == this.flights + 1) {
this.result = (List<String>) route.clone();
return true;
}
if (!this.flightMap.containsKey(origin))
return false;
int i = 0;
boolean[] bitmap = this.visitBitmap.get(origin);
for (String dest : this.flightMap.get(origin)) {
if (!bitmap[i]) {
bitmap[i] = true;
route.add(dest);
boolean ret = this.backtracking(dest, route);
route.pollLast();
bitmap[i] = false;
if (ret)
return true;
}
++i;
}
return false;
}
}它的时间复杂度和空间复杂度分析

10
收起
正在回答 回答被采纳积分+1
1回答
liuyubobobo
2022-01-27 09:20:53
整体上,你可以理解成,回溯算法的时间复杂度一定是指数级。因为回溯算法是一棵递归树,在每一层有 x 个选择,一共 k 层,则其时间复杂度就是 O(x^k) 的。在这个问题里,每一层有 |E| 个选择,一共 d 层,所以是 |E|^d 的。
继续加油!:)
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星