【问题标题】:ArrayList of int[] in a recursive method递归方法中 int[] 的 ArrayList
【发布时间】:2017-08-22 20:44:24
【问题描述】:

我有一个项目要为学校做,我必须使用递归方法来计算一些数字之间的所有切换可能性。 即:[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 是空的。

希望你能帮忙,谢谢!

【问题讨论】:

    标签: java loops recursion arraylist


    【解决方案1】:

    问题是您正在向 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]
    

    【讨论】:

    • 感谢老兄,它成功了!但是我能问你我的线和深拷贝的区别吗?我的意思是什么时候应该在输入引用上使用深拷贝?
    • 您想在任何时候使用深拷贝来获取对象的真正新副本,而不仅仅是对对象的当前引用的副本。后者不会保护您免受其他代码通过它们持有的引用修改底层对象的影响,这正是您在这里绊倒的原因。要理解为什么这是必要的,谷歌搜索“java 是按引用传递还是按值传递?”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2017-08-07
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多