Obtaining a powerset of a set in Java

Yes, it is O(2^n) indeed, since you need to generate, well, 2^n possible combinations. Here’s a working implementation, using generics and sets: public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { Set<Set<T>> sets = new HashSet<Set<T>>(); if (originalSet.isEmpty()) { sets.add(new HashSet<T>()); return sets; } List<T> list = new ArrayList<T>(originalSet); T head = list.get(0); Set<T> rest = new … Read more

How to get all subsets of a set? (powerset)

The Python itertools page has exactly a powerset recipe for this: from itertools import chain, combinations def powerset(iterable): “powerset([1,2,3]) –> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)” s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) Output: >>> list(powerset(“abcd”)) [(), (‘a’,), (‘b’,), (‘c’,), (‘d’,), (‘a’, ‘b’), (‘a’, ‘c’), (‘a’, ‘d’), (‘b’, ‘c’), (‘b’, … Read more