8.3 Write a method that returns all subsets of a set.
powerSet(i) = [powerSet(i - 1)] * ITEMi + // Add new item into each existing set [pwerSet(i - 1)] + // Existing set ITEMi // single new item. powerSet(1) = ITEM1. <T> Set<Set<T>> powerSet(Set<T> set) { if (set == null || set.isEmpty()) return Collections.emptyList(); Set<Set<T>> toReturn = Sets.new(); T t = set.removeFirstElement(); Set<Set<T>> smallResults = powerSet(set); toReturn.addAll(smallResults); for (Set<T> s : smallResults) { Set<T> withI = Sets.copy(s).add(t); toReturn.add(withI); } toReturn.add(Sets.of(t)); // Add empty one in outer method. // if needed. toReturn.add(Sets.empty()); return toReturn; }
时间: 2024-10-04 09:25:29