数据结构与算法分析Java版练习1.6

package ch01;

/**
 * 练习1.6 编写带有下列声明的例程:
 * public void permute(String str);
 * public void permute(char[] str, int low, int high);
 * 第一个例程是个驱动程序,它调用第二个例程并显示String str中的字符的所有排列。如果
 * str是"abc",那么输出的串则是abc,acb,bac,bca,cab和cba。第二个例程使用递归。
 * 
 */
public class EX06 {
	public static void permute(String str) {
		char[] chars = str.toCharArray();
		permute(chars, 0, chars.length - 1);
	}
	
	public static void permute(char[] str, int low, int high) { 
		if (low == high){
			String cout = ""; 
			for (int i = 0;i <= high;i++)
				cout += str[i];
			System.out.println(cout);
		} else {   
			for (int i = low; i <= high; i++) {   
				swap(str, low, i);
				permute(str, low + 1, high);
				swap(str, low, i);
			}   
		}   
	}
	
	private static void swap(char[] str, int i, int j) {
		char temp = str[i];
		str[i] = str[j];
		str[j] = temp;
	}
	
	public static void main(String[] args) {
		String str = "abcd";
		permute(str);
	}
}

猜你喜欢

转载自blog.csdn.net/zhangyingli/article/details/48087015