I am trying to find the subsets of an array. In example if the array is [1,2] I am trying to print the following:
[1][2]
[1]
[2]
null
The code that I have written is as follows:
import java.util.*;
class PrintArray {
public static void printme(int a[], int pos, int size) {
if (pos >= size)
return;
else
System.out.println(a[pos]);
pos++;
printme(a, pos, size);
}
public static void generate(int a[], ArrayList<Integer> list, int pos, int size) {
if (pos > size) {
for (int i = 0; i < list.size() - 1; i++) {
System.out.print("[" + list.get(i) + "]");
}
System.out.println();
return;
}
list.add(a[pos]);
generate(a, list, pos + 1, size);
list.remove(list.size() - 1);
generate(a, list, pos + 1, size);
}
public static void main(String args[]) {
int ar[] = { 1, 2, 3, 4, 5 };
// printme(ar, 0, ar.length);
ArrayList<Integer> list = new ArrayList<Integer>();
generate(ar, list, 0, ar.length);
}
}
However I am running into the following OOBE error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds
That can be resolved by checking for pos>=size instead of pos>size but such a change does not generate all the sub-arrays.
A follow-up problem is that I am getting duplicate outputs as shown below:
[2][3][4]
[2][3]
[2][3]
[2]
[2][4]
[2]
[2]
Could someone please help me in overcoming these 2 issues?