标签:interview
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; }
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1585016