2015-06-21 45 views
1

陣列的所有可能的子序列我打算找一個數組的所有可能的子序列用java

我試圖做到這一點在兩種不同的方式

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

問題的值---僅適用於單個數字字符

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

問題 - 它僅例如子陣列生成用於陣列2 5 9 我得到---- [2] [2,5] [-2,5,9-] [5] [5] [9] 但它錯過[2,9]

所以任何人都可以幫助我這個代碼?

+1

您應該添加Java標記,因爲它是您正在使用的語言。 –

回答

5

這是一段代碼片段,這個想法是:將元素添加到序列中並添加到之前的所有元素,這是您想要的嗎?不檢查序列是否已經存在。

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