Last active
July 11, 2018 04:36
-
-
Save sreeprasad/fdcd21f9397e78136e12e53267057357 to your computer and use it in GitHub Desktop.
Simple Recursive way of printing all the subsets of an array.
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 void printAllSubsets(int[] input){ | |
if ((input == null) || (input.length == 0)) return; | |
int N = input.length; | |
int [] output = new int[N]; | |
printAllSubsets(input, 0, output, 0); | |
} | |
private void printAllSubsets(int [] input, int read, int [] output, int write) { | |
if(read == input.length){ | |
print(write); | |
return; | |
} | |
// recurse without taking the current element | |
printAllSubsets(input, read+1, output, write); | |
// recurse taking the current element | |
output[write] = input[read] | |
printAllSubsets(input, read+1, output, write+1); | |
} | |
private void print(int[] array) { | |
System.out.println(Arrays.toString(array)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment