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

标签 java arrays

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

我尝试了两种不同的方式

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");
    }
 }

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

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();
     }
  }

问题 -- 它只为数组 2 5 9 生成子数组 我得到 ---- [2] [2,5] [2,5,9] [5] [5,9] [9] 但是它错过了 [2,9]

那么有人可以帮我处理这段代码吗?

最佳答案

这是一个代码片段,思路是:将元素添加到序列和之前的所有元素中,是你想要的吗?不检查序列是否已存在。

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;
}

关于java - 使用java的数组的所有可能子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966507/

相关文章:

php - 如何将 php 中的二维数组旋转 90 度

c++ - 使用 C++ new[] 为二维数组分配内存

javascript - 使用 JQuery 循环遍历数组值并将它们显示在单独的行上

java - 在java泛型中创建子类元素列表

java - 如何在实用程序类对象的属性中使用别名拦截器

java - 在Java中运行Linux命令时出现IO异常

javascript - 过滤方法的可变过滤标准

python - 更快地填写列表

java - 当JAVA中不存在REST API方法时返回JSON而不是html错误页面

java - 如何在 XML 已经工作的情况下添加 JSON 支持?