使用递归实现全排列的算法

在这一篇中,我们来讲如何用递归来实现字符的全排列算法,当然同样适用于其他的数据类型,不多说了,直接上代码:

	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;
	}

}
笔者在后面会有补充,先看一看运行结果:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值