试图重现堆的算法,以生成整数数组的所有可能排列,但我无法解决除三个以外的其他整数。来自维基百科的堆算法:
procedure generate(N : integer, data : array of any):
if N = 1 then
output(data)
else
for c := 1; c <= N; c += 1 do
generate(N - 1, data)
swap(data[if N is odd then 1 else c], data[N])
我的代码:
public static void perm(int[] list, int n){
if(n==1){
System.out.println(Arrays.toString(list));
} else {
for(int c=1;c<=n;c++){ /for(int c=0;c<n;c++)
perm(list,n-1);
if(n%2==0){
int temp1=list[c]; //This is line 17
list[c]=list[list.length-1];
list[list.length-1]=temp1;
}else{
int temp2=list[0];
list[0]=list[list.length-1];
list[list.length-1]=temp2;
}
}
}
}
我在做什么错和误解?为什么它仅适用于 [1,2,3] (n=3) 作为输入,而不适用于 n=2 或 n=4?
运行:
perm(A,3);
[1, 2, 3]
[1, 3, 2]
[2, 3, 1]
[2, 1, 3]
[3, 1, 2]
[3, 2, 1]
perm(A,4)
[1, 2, 3, 4]
[1, 4, 3, 2]
.
.
.
[2, 4, 1, 3]
[2, 3, 1, 4]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Permutation.perm(Permutation.java:17)
at Permutation.main(Permutation.java:43)
感谢您的回复,但这不是问题。在我问这个问题之前,我尝试改变它,但是如果我正确理解了 Wiki 页面,我认为从 1 开始是算法的一部分,因为它明确说明(即使没有提到特定的语言/for-loop-scheme)。下面是 n=4 的输出,其中包含多个重复项。链接到 Wiki 页面:http ://en.wikipedia.org/wiki/Heap%27s_algorithm
[1, 2, 3, 4]
[4, 2, 3, 1]
[2, 1, 3, 4]
[4, 1, 3, 2]
[1, 2, 3, 4]
[4, 2, 3, 1]
[4, 1, 3, 2]
[2, 1, 3, 4]
[1, 4, 3, 2]
[2, 4, 3, 1]
[4, 1, 3, 2]
[2, 1, 3, 4]
[1, 2, 3, 4]
[4, 2, 3, 1]
[2, 1, 3, 4]
[4, 1, 3, 2]
[1, 2, 3, 4]
[4, 2, 3, 1]
[2, 1, 4, 3]
[3, 1, 4, 2]
[1, 2, 4, 3]
[3, 2, 4, 1]
[2, 1, 4, 3]
[3, 1, 4, 2]