leetcode 332题

来源:1-1 哈希表基础

weixin_慕圣6334738

2022-01-27 04:19:05

老师你好,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;
  }
}

它的时间复杂度和空间复杂度分析


https://img.mukewang.com/climg/61f1acb10955dac708440478.jpg


写回答

1回答

liuyubobobo

2022-01-27

整体上,你可以理解成,回溯算法的时间复杂度一定是指数级。因为回溯算法是一棵递归树,在每一层有 x 个选择,一共 k 层,则其时间复杂度就是 O(x^k) 的。在这个问题里,每一层有 |E| 个选择,一共 d 层,所以是 |E|^d 的。


继续加油!:) 

0
hiuyubobobo
回复
heixin_慕圣6334738
hp>对于一个图,使用邻接表存储,所需要的时间复杂度就是 O(V + E) 的,即所有的点 + 所有的边都记录。

h022-01-27
共2条回复

算法与数据结构

波波老师5年集大成之作,算法与数据结构系统学习,考试、面试、竞赛通用

2636 学习 · 1090 问题

查看课程

相似问题

leetcode 1248

回答 1

leetcode 907

回答 1

Leetcode 146

回答 1

回答 1