Skip to content

Instantly share code, notes, and snippets.

@hatakawas
Last active February 23, 2017 10:42
Show Gist options
  • Save hatakawas/3f4a6f6b0668ead2bf6c0260ba2009a7 to your computer and use it in GitHub Desktop.
Save hatakawas/3f4a6f6b0668ead2bf6c0260ba2009a7 to your computer and use it in GitHub Desktop.
public class Subset {
@SafeVarargs
public static <T> List<List<T>> subsets(T... items) {
List<T> elements = new ArrayList<>(new HashSet<>(Arrays.asList(items)));
List<List<T>> results = new ArrayList<>();
for (T e : elements) {
// Record size as the list will change
int size = results.size();
for (int i = 0; i < size; i++) {
List<T> subset = new ArrayList<>(results.get(i));
subset.add(e);
results.add(subset);
}
results.add(Collections.singletonList(e));
}
return results;
}
public static void main(String[] args) {
List<List<String>> results = subsets("a", "b", "c");
for (List<String> result : results) {
System.out.println(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment