I need to find all the subsets of an array using java.For e.g. if we have a set {1,2,3} then i should get {},{1},{2},{3},{1,2},{2,3},{1.3},{1,2,3}
Asked
Active
Viewed 2,566 times
-8
-
1Write a recursive method, to which you can initially pass every element individually, then two at a time and there on. – Saurabh Jhunjhunwala Apr 28 '15 at 12:44
-
3Have you tried to code something ? – JFPicard Apr 28 '15 at 12:45
-
@SaurabhJhunjhunwala: If you do it that way you need to take care not to emit duplicates. – Bathsheba Apr 28 '15 at 12:45
-
@Bathsheba: It actually depends on your implementation process. you keep passing values from the first element to the last. DO NOT TRY TO COMBINE WITH PREVIOUS ELEMENTS. Secondly, still if you feel there is a probability, keep adding the generated sets to a parent set. – Saurabh Jhunjhunwala Apr 28 '15 at 12:51
1 Answers
-1
You can do this to avoid needing to recurse the solutions.
public static <T> void printCombinations(T[] arr) {
for(long i = 0, max = 1L << arr.length; i < max; i++) {
Set<T> ts = new HashSet<>();
for(int j = 0; j < arr.length; j++) {
if ((i >> j) != 0)
ts.add(list.get(j));
}
System.out.println(ts);
}
}

Peter Lawrey
- 525,659
- 79
- 751
- 1,130