Java 如何优化我的DAG调度解决方案?
我试图解决LeetCode问题,但得到了LTE。问题是 这是我的Java 如何优化我的DAG调度解决方案?,java,graph,permutation,directed-acyclic-graphs,topological-sort,Java,Graph,Permutation,Directed Acyclic Graphs,Topological Sort,我试图解决LeetCode问题,但得到了LTE。问题是 这是我的Kahn+Permutations基于O(V!)复杂性的解决方案。它在11[]2上获得TLE。我认为这是O(V!),因为数组排列的复杂性加起来就是O(n!) 这是一种不可接受的复杂性,还是我的“排列”可以通过任何方式得到改进,例如,修剪递归?如果没有,你能给我一个更好、更容易理解的建议吗 class Solution { public int minNumberOfSemesters(final int n, fi
Kahn+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, i, inDegree, seq, combinations);
}
}
for (final int adj: adjs) {
inDegree[adj]++;
}
}
seq.remove(seq.size() - 1);
graph.put(vertex, adjs);
}
}
类解决方案{
公共整数minnumberofsemeters(最终整数n,最终整数[][]边,最终整数k){
最终映射图=新HashMap();
对于(int i=1;i