使用java的数组的所有可能子序列

cod*_*101 1 java arrays

我打算找到一个数组的所有可能的子序列

我尝试用两种不同的方式做到这一点

1)方法1

我用数组中的值创建一个字符串

// 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");
    }
 }
Run Code Online (Sandbox Code Playgroud)

问题---仅适用于单个数字字符

2)方法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();
     }
  }
Run Code Online (Sandbox Code Playgroud)

问题 - 它只生成子阵列,例如阵列2 5 9我得到---- [2] [2,5] [2,5,9] [5] [5,9] [9]但是它没错过[2,9]

那么有人可以帮我这个代码吗?

mar*_*aca 6

这是一个代码片段,想法:将元素添加到序列和所有以前的元素,它是你想要的吗?不检查序列是否已存在.

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;
}
Run Code Online (Sandbox Code Playgroud)