【发布时间】:2015-06-26 17:32:45
【问题描述】:
我阅读了一种用于递归生成字符串排列的算法。
invoke the function with j = 1 if (j == length of string) print the string and return else for (i = j to length of string) interchange jth character with ith character call function on j + 1
我使用 java 实现了如下:
class PERMUTATION {
private int count = 1;
private char[] arr = {'A', 'B', 'C'};
public void perm(int k) {
if (k == 3) {
System.out.print(count+++".");
for (int i = 0; i < 3; ++i)
System.out.print(arr[i]+" ");
System.out.println();
return;
}
for (int i = k; i <= 3; ++i) {
/*interchanging ith character with kth character*/
char c = arr[i - 1];
arr[i - 1] = arr[k - 1];
arr[k - 1] = c;
perm(k + 1);
}
}
public static void main(String []args) {
System.out.println("the permutations are");
PERMUTATION obh=new PERMUTATION();
obh.perm(1);
}
}
但是我的程序产生了重复的排列。为什么?
【问题讨论】:
标签: java recursion permutation