package com.igeek;
import org.junit.Test;
/**
*
* @ClassName: Test03
* @Description: 将多个不同字符的所有排列方式输出
* @date 2019年7月16日 下午7:02:04
* Company www.igeekhome.com
*
*/
public class Test03 {
@Test
public void demo() {
char[] cs = { 'a', 'b', 'c' ,'d'};
recursionSwap(cs, 0, cs.length);
}
public void recursionSwap(char[] cs, int start, int length) {
if (start >= length - 1) {
print(cs);
return;
}
for (int i = start; i < length; i++) {
//位置互换
swap(cs, start, i);
recursionSwap(cs, start + 1, length);
swap(cs, start, i);
}
}
public void swap(char[] cs, int index1, int index2) {
char temp = cs[index1];
cs[index1] = cs[index2];
cs[index2] = temp;
}
public void print(char[] cs){
for(int i=0;i<cs.length;i++){
System.out.print(cs[i]);
}
System.out.println();
}
}
另一种方法
public class Test05 {
// n表示的是定义全排列的位数,可以根据题目意思和实际情况自行输入自行定义
public static int n = 4;
public static char a[] = new char[5]; // 存储结果的数组的大小
public static int book[] = new int[91]; // 大写字母的ASCII码值在65-91
public static void main(String[] args) {
dfs(1);
}
private static void dfs(int temp) {
if (temp == n + 1) {
System.out.printf("%c%c%c%c \n", a[1], a[2], a[3], a[4]);
return;
}
for (int i = 'A'; i <= 'D'; i++) {// 也可以使用ASCII码在做i的取值范围
if (book[i] == 0) {
a[temp] = (char) i;
book[i] = 1;
dfs(temp + 1);
book[i] = 0;
}
}
return;
}
}