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

时间:2015-06-21 16:04:05

标签: java arrays

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

我试图以两种不同的方式做到这一点

1)方法1

我使用数组

中的值创建一个字符串
class Program
{
    static double[] a1;
    static double[] a2;

    static double b1;
    static double b2;

    static void Main(string[] args)
    {
        //First example
        a1 = new double[5] { 1,2,3,4,5 };
        a2 = new double[5] { 6,7,8,9,10};

        a2 = a1;
        a1[2] = 99;  //I change only a1

        Console.WriteLine(a1[2]);        
        Console.WriteLine(a2[2]);
        //Result is:
        // 99
        // 99   why is a2 changed too?       


        //Second example 
        b1 = new double(); 
        b2 = new double(); 
        b1 = 10;
        b2 = 20;

        b2 = b1;
        b1 = 33;

        Console.WriteLine(b1);
        Console.WriteLine(b2);
        //Result is:
        // 33     
        // 10   this is okay
    }
}

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

2)方法2

// 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 5 9生成子数组 我得到---- [2] [2,5] [2,5,9] [5] [5,9] [9] 但它错过了[2,9]

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

1 个答案:

答案 0 :(得分: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;
}