2016-12-05 44 views
0

所以我非常接近解決這個算法。這是另一個更長的算法的一部分,我只是讓它找到ArrayList中所有可能的整數有序組合。書寫組合遞歸地使用Java中的整數ArrayList

我有一個整數{0,1,2}的ArrayList。我想通過使用成員方法permute()來有效地使用遞歸來解決這個問題。我有原始ArrayList {0,1,2},並使用ArrayList preArr使用ArrayList助手一個接一個地填充它,直到preArr填充項目,然後嘗試清除preArr和助手以重新填充新組合。

public class ArrayPermutation { 

    ArrayList<Integer> arr = new ArrayList<>(); 

    public ArrayPermutation(int N) { 
     for (int i = 0; i < N; i++) { 
      arr.add(i); 
      //System.out.println("Arr at index " + i + " ===> " + arr[i]); 
     } 

    } 

    public static void main(String[] args) { 
     // Test an integer array and pring all posible combinations 
     int N = 3; 
     ArrayPermutation a = new ArrayPermutation(N); 
     a.solver(N); 
    } 

    public void solver(int N) { 
     ArrayList<Integer> pArr = new ArrayList<>(); 
     ArrayList<Integer> preArr = new ArrayList<>(); 

     for (int i = 0; i < N; i++) { 
      pArr.add(i); 
     } 
     permute(preArr, pArr, N); 
    } 

    public void permute(ArrayList<Integer> preArr, ArrayList<Integer> pArr, int N) { 

     int n = pArr.size(); 
     ArrayList<Integer> helper = new ArrayList<>(); 

     if(n == 0){ 
      for (int i = 0; i < preArr.size(); i++) { 
       System.out.print(preArr.get(i) + " "); 
      } 
      System.out.println(""); 
     } else { 
      for (int i = 0; i < n; i++) { 
       for(int j = 0; j < n; j++){ 
        if(j == i) 
        { 
         preArr.add(pArr.get(j)); 
        } 
        else { 
         helper.add(pArr.get(j)); 
        } 

       } 
       permute(preArr, helper, N); 
       preArr.clear(); 
       helper.clear(); 
      } 

     } 

    } 

} 

從這裏,我有以下。

Expected Output 
0 1 2 
0 2 1 
1 0 2 
1 2 0 
2 0 1 
2 1 0 

Actual Output 
0 1 2 
2 1 
1 0 2 
2 0 
2 0 1 
1 0 

因此,你可以看到我錯過了第二個列表中的第一個整數。我知道我很接近,但我在解決這個特定問題時遇到了一些麻煩。我已經看過使用其他來源的一些幫助,但要弄清我的具體示例有點棘手。我很感激任何幫助!

回答

0

在完成該組排列之前,您正在清除preArr。您可能想要刪除最後一個元素。

+0

哇!所以我用preArr.remove(preArr.size() - 1)替換了preArr.clear(),它工作正常!我感覺有點笨拙,但現在鬆了一口氣,謝謝你指出了這一點,這讓我有更長的時間去理解我自己。 –