如何优化我的 DAG 调度解决方案?

问题描述

我试图解决 LeetCode 问题,但得到了 LTE。问题是https://leetcode.com/problems/parallel-courses-ii

这是我基于 Kahn's + Permutations解决方案,具有 O(V!) 的复杂性。它在 11 [] 2 上获得 TLE。我认为它是 O(V!),因为数组排列的复杂性加起来为 O(n!)

这是完全不可接受的复杂性还是可以以任何方式改进我的“排列”,例如,通过修剪递归?如果没有,您能否就更好且易于理解的方法向我提出建议?

class Solution {
    
    public int minNumberOfSemesters(final int n,final int[][] edges,final int k) {
        final Map<Integer,List<Integer>> graph = new HashMap<>();
        for (int i = 1; i <= n; i++) {
            graph.put(i,new ArrayList<>());
        }
        final int[] inDegree = new int[n + 1];
        for (final int[] dep: edges) {
            graph.get(dep[0]).add(dep[1]);
            inDegree[dep[1]]++;
        }
        final List<Integer> seq = new ArrayList<>();
        final List<List<Integer>> combinations = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            if (inDegree[i] == 0) {
                combinations(graph,i,inDegree,seq,combinations);
            }
        }
        int result = n;
        for (final List<Integer> combination: combinations) {
            int counter = 1,w = 0;
            final Set<Integer> dependents = new HashSet<>();
            for (final int course: combination) {
                if (dependents.contains(course) || w == k) {
                    counter++;
                    w = 0;
                    dependents.clear();
                }
                w++;
                dependents.addAll(graph.get(course));
            }
            result = Math.min(result,counter);
        }
        return result;
    }

    public void combinations(final Map<Integer,List<Integer>> graph,final int vertex,final int[] inDegree,final List<Integer> seq,final List<List<Integer>> combinations) {
        final List<Integer> adjs = graph.remove(vertex);
        if (adjs == null) {
            return;
        }
        seq.add(vertex);
        if (seq.size() == inDegree.length - 1) {
            combinations.add(new ArrayList<>(seq));
        } else {
            for (final int adj: adjs) {
                inDegree[adj]--;
            }
            for (int i = 1,n = inDegree.length; i < n; i++) {
                if (inDegree[i] == 0) {
                    combinations(graph,combinations);
                }
            }
            for (final int adj: adjs) {
                inDegree[adj]++;
            }
        }
        seq.remove(seq.size() - 1);
        graph.put(vertex,adjs);
    }

}

我在 LC 上的帖子:https://leetcode.com/problems/parallel-courses-ii/discuss/1243768/how-to-pruneoptimize-my-java-solution

AFAIK,在 O(V + E) 中没有贪心的方法

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)