Reputation: 850
I intend to find all possible subsequences of an array
I tried to do it in 2 different ways
1) Method 1
I create a string with the values in array
// all possible subsequences - all possible elements found by eleiminating zero or more characters
Public class StrManipulation{
public static void combinations(String suffix,String prefix){
if(prefix.length()<0)return;
System.out.println(suffix);
for(int i=0;i<prefix.length();i++)
combinations(suffix+prefix.charAt(i),prefix.substring(i+1,prefix.length()));
}
public static void main (String args[]){
combinations("","12345");
}
}
Problem --- works only for single digit characters
2) Method 2
int a[] = new int[3];
a[0]=2;a[1]=3;a[2]=8;
List<Integer> al= new ArrayList<Integer>();
for(int i=0;i<3;i++)
al.add(a[i]);
int i, c;
for( c = 0 ; c < 3 ; c++ )
{
for( i = c+1 ; i <= 3 ; i++ )
{
List<Integer> X = al.subList(c,i);
for(int z=0;z<X.size();z++)
System.out.print(X.get(z)+" ");
System.out.println();
}
}
Problem -- It generates subarrays only for example for an array 2 5 9 I get ---- [2] [2,5] [2,5,9] [5] [5,9] [9] But it misses [2,9]
So can anyone help me with this code?
Upvotes: 1
Views: 9069
Reputation: 8743
Here is a code snippet, the idea: add the element to the sequence and to all previous ones, is it what you want? It is not checked if a sequence already exists.
public List<List<Integer>> combinations(int[] arr) {
List<List<Integer>> c = new ArrayList<List<Integer>>();
List<Integer> l;
for (int i = 0; i < arr.length; i++) {
int k = c.size();
for (int j = 0; j < k; j++) {
l = new ArrayList<Integer>(c.get(j));
l.add(new Integer(arr[i]));
c.add(l);
}
l = new ArrayList<Integer>();
l.add(new Integer(arr[i]));
c.add(l);
}
return c;
}
Upvotes: 7