Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@happyWinner
Created August 8, 2014 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happyWinner/51c1887f3c0d58232988 to your computer and use it in GitHub Desktop.
Save happyWinner/51c1887f3c0d58232988 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
/**
* Write a method to return all subsets of a set.
*
* Time Complexity: O(2^n)
* Space Complexity: O(2^n)
*/
public class Question9_4 {
public LinkedList<LinkedList<Integer>> subsets(int[] set) {
LinkedList<LinkedList<Integer>> subsets = new LinkedList<LinkedList<Integer>>();
if (set != null && set.length != 0) {
subsets.add(new LinkedList<Integer>());
for (int i = 0; i < set.length; ++i) {
int size = subsets.size();
for (int j = 0; j < size; ++j) {
LinkedList<Integer> subset = new LinkedList<Integer>(subsets.get(j));
subset.add(set[i]);
subsets.add(subset);
}
}
}
return subsets;
}
public static void main(String[] args) {
Question9_4 question9_4 = new Question9_4();
LinkedList<LinkedList<Integer>> subsets = question9_4.subsets(new int[] {0, 1, 2});
for (int i = 0; i < subsets.size(); ++i) {
System.out.println(subsets.get(i).toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment