簡體   English   中英

遞歸方法中int []的ArrayList

[英]ArrayList of int[] in a recursive method

我有一個學校項目,必須使用一種遞歸方法來計算一些數字之間的所有切換可能性。 IE:[1,2] => 1,2和2,1。

所以我使用了這種方法,當我只在控制台上打印解決方案時,它似乎可以正常工作,但是當我想將選項卡存儲在ArrayList中時(我以后需要使用它們),它將總是添加相同的順序。 在我的例子中,它將增加1,2和1,2,而不是1,2和2,1。

這是我的代碼:

public  static void permute(int start, int[] input, ArrayList <int[]> al) { 
    //This method is recursive, it will open multiple instances of the input tab by calling itself and modify them, then stock tab in ArrayList when the operations are done for this tab.
    //ArrayList must be empty.

    //Printing tab if iterations for that specific tab are done
    if (start == input.length) {
        al.add(input);
        ////////////////////////////////
        // For printing tabs in console.
        // for(int x: input){
        // System.out.print(x);
        // }
        // System.out.println("");
        ////////////////////////////////
    //End the specific tab loop when it's printed 

    return;
    }
    for (int i = start; i < input.length; i++) {
        // Changing numbers
        int temp = input[i];
        input[i] = input[start];
        input[start] = temp;

        //////////////////////////////////////////////////
        // Tests to see algorithm steps
        //
        // System.out.print("temp : " + temp + " ... ");
        // System.out.print("i : "+i + " ... ");
        // System.out.print("start : " + start);
        // System.out.println("");
        // System.out.print("---");
        // for(int x: input){
        //  System.out.print(x);
        // }
        // System.out.println("");
        //////////////////////////////////////////////////

        //Changing numbers
        permute(start + 1, input, al);

       // Changing numbers
        int temp2 = input[i];
        input[i] = input[start];
        input[start] = temp2;

}

}

我使用start = 0,input = {1,2,3},並且在方法開始之前ArrayList為空。

希望能對您有所幫助,謝謝!

問題是您要在ArrayList中添加對數組的引用,然后在您的算法中不斷更改引用。

到最后,您將擁有同一陣列的perm(N)個副本。

您要做的就是將數組的深層副本添加到ArrayList中,如下所示:

al.add(Arrays.copyOf(input, input.length));

代替

al.add(input);

打印結果ArrayList將產生以下輸出:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM