力扣labuladong一刷day69天回溯大集合

力扣labuladong一刷day69天回溯大集合

一、332. 重新安排行程

题目链接:https://leetcode.cn/problems/reconstruct-itinerary/description/
思路:本质上还是回溯题,依然是带有排序的性质,for循环不需要起始位置,先把数组按照字典序排序,然后第一次找到行程后直接早停,即可完成该题,不过目前使用递归超时了,只能用优先级队列了。

class Solution {
    LinkedList<String> strings ;
    LinkedList<String> list = new LinkedList<>();
    public List<String> findItinerary(List<List<String>> tickets) {
        Collections.sort(tickets, (a, b) -> a.get(1).compareTo(b.get(1)));
        list.add("JFK");
        boolean[] used = new boolean[tickets.size()];
        backTracking(tickets, used);
        return strings;
    }
    boolean backTracking(List<List<String>> tickets, boolean[] used) {
        if (list.size() == used.length + 1) {
            strings = new LinkedList<>(list);
            return true;
        }
        for (int i = 0; i < tickets.size(); i++) {
            if (!used[i] && tickets.get(i).get(0).equals(list.getLast())) {
                list.add(tickets.get(i).get(1));
                used[i] = true;

                if (backTracking(tickets, used)) {
                    return true;
                }
                list.removeLast();
                used[i] = false;
            }
        }
        return false;
    }
}

采用优先级队列和深度优先。

class Solution {
    List<String> list = new ArrayList<>();
    Map<String, PriorityQueue<String>> map = new HashMap<>();

    public List<String> findItinerary(List<List<String>> tickets) {

        for (List<String> ticket : tickets) {
            String key = ticket.get(0);
            String value = ticket.get(1);
            if (!map.containsKey(key)) {
                map.put(key, new PriorityQueue<>());
            }
            map.get(key).add(value);
        }
        dfs("JFK");
        Collections.reverse(list);
        return list;
    }
    public void dfs(String src) {
        while (map.containsKey(src) && map.get(src).size() > 0) {
            dfs(map.get(src).poll());
        }
        list.add(src);
    }
}

你可能感兴趣的:(力扣算法题,leetcode,算法,职场和发展)