Last active
February 23, 2017 10:42
-
-
Save hatakawas/3f4a6f6b0668ead2bf6c0260ba2009a7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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