在这一篇中,我们来讲如何用递归来实现字符的全排列算法,当然同样适用于其他的数据类型,不多说了,直接上代码:
private static void doAnagram(int size2) { //进行递归调用,不断的调用自己,将n-1个元素进行转换,并且进行n次的循环。此处需要重点理解
if (size2 == 1) {
return;
}
for (int i = 0; i < size2; i++) {
doAnagram(size2 - 1);
if (size2 == 2) {
displayWord();
}
rotate(size2);
}
}
这个递归调用在于通过不断的调用自己,传入的是字符串的长度,所以进行长度的递减,当长度为一的时候,也就是只有一个字符,将其直接返回值,便 直接可以打印出字符数组中的值了,这是第一次,后面的每一次都经过转换,如何转换的:
private static void rotate(int size2) { //轮换最后一个元素的值,对第n-1个元素进行不断的轮换
int j;
int position = size - size2;
char temp = arrchar[position];
for (j = position + 1; j < size; j++) {
arrchar[j - 1] = arrchar[j];
}
arrchar[j - 1] = temp;
}
通过对n-1个元素,进行不断的轮换,从而实现了排列的目的,笔者可能讲的不够清楚,大家请仔细看代码,认真思考一下,建议可以画一画来形象认识。下面是整个程序的源码:
public class RecursionTest {
static int size;
static int count;
static char[] arrchar = new char[100];
public static void main(String[] args) throws IOException {
System.out.print("Enter a word : ");
String input = getString();
size = input.length();
count = 0;
for (int i = 0; i < size; i++) {
arrchar[i] = input.charAt(i);
}
doAnagram(size);
}
private static void doAnagram(int size2) { //进行递归调用,不断的调用自己,将n-1个元素进行转换,并且进行n次的循环。此处需要重点理解
if (size2 == 1) {
return;
}
for (int i = 0; i < size2; i++) {
doAnagram(size2 - 1);
if (size2 == 2) {
displayWord();
}
rotate(size2);
}
}
private static void rotate(int size2) { //轮换最后一个元素的值,对第n-1个元素进行不断的轮换
int j;
int position = size - size2;
char temp = arrchar[position];
for (j = position + 1; j < size; j++) {
arrchar[j - 1] = arrchar[j];
}
arrchar[j - 1] = temp;
}
private static void displayWord() { //将此时字符数组中的所有元素都打印出来
if (count < 99) {
System.out.print(" ");
}
if (count < 9) {
System.out.print(" ");
}
System.out.print(++count + " ");
for (int j = 0; j < size; j++) {
System.out.print(arrchar[j]);
}
System.out.print(" ");
System.out.flush();
if (count % 6 == 0) {
System.out.println("");
}
}
public static String getString() throws IOException { //输入流的转换
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(inputStreamReader);
String s = buf.readLine();
return s;
}
}
笔者在后面会有补充,先看一看运行结果: