【发布时间】: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