public static Set<Set> powerSet(Set set) {
Set<Set> powerSet = new HashSet();
if (set.isEmpty()) {
powerSet.add(new HashSet());
return powerSet;
}
List list = new ArrayList(set);
Object head = list.get(0);
Set rest = new HashSet(list.subList(1, list.size()));
for (Set subset : powerSet(rest)) {
Set newSubset = new HashSet();
newSubset.add(head);
newSubset.addAll(subset);
powerSet.add(newSubset);
powerSet.add(subset);
}
return powerSet;
}
public static Set<Set> powerSet(Set set) {
Set<Set> powerSet = new HashSet();
int n = set.size();
int size = 1 << n;
List list = new ArrayList(set);
for (int i = 0; i < size; i++) {
Set subset = new HashSet();
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
subset.add(list.get(j));
}
}
powerSet.add(subset);
}
return powerSet;
}
// 假设有一个图graph,其中包含n个顶点和m条边,表示为edges
Set vertices = new HashSet();
for (int i = 0; i < n; i++) {
vertices.add(i);
}
Set<Set> powerset = powerSet(vertices);
int minWeight = Integer.MAX_VALUE;
Set minSpanningTree = null;
for (Set verticeset : powerset) {
Set edgeset = new HashSet();
for (int i = 0; i < m; i++) {
if (verticeset.contains(edges[i].v1) && verticeset.contains(edges[i].v2)) {
edgeset.add(i);
}
}
// 计算边集的权值之和,从而得到最小生成树
}
最新评论