Created
March 21, 2020 17:49
-
-
Save mekilis/4e14befc89d114e9be5d32ab7cb51f3b to your computer and use it in GitHub Desktop.
This function generates and returns all subsets of a list using recursion
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
private static int numberOfElements; | |
private static List<List<Integer>> subsets; | |
private static List<Integer> currentSubset, elements; | |
private static List<List<Integer>> subsetRecursive(List<Integer> elementsArg) { | |
elements = elementsArg; | |
numberOfElements = elements.size(); | |
subsets = new ArrayList<>(); | |
currentSubset = new ArrayList<>(); | |
System.out.println("Subsets of " + elements); | |
subset(0); | |
return subsets; | |
} | |
private static void subset(int index) { | |
if (index == numberOfElements) { | |
System.out.println(String.format("%s: %s", convertToZeroPaddedBinaryString(subsets.size(), numberOfElements), currentSubset)); | |
subsets.add(new ArrayList<>(currentSubset)); // clone original subset | |
} else { | |
subset(index+1); | |
currentSubset.add(elements.get(index)); | |
subset(index+1); | |
currentSubset.remove(currentSubset.size()-1); // pop last element from the subset | |
} | |
} | |
private static String convertToZeroPaddedBinaryString(int number, int padWidth) { | |
return String.format("%" + padWidth + "s", Integer.toBinaryString(number)).replaceAll(" ", "0"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment