这道题其实和上一篇文章《含重复字符的字符数组的全排列》代码很相似,这是做了一点改进,删除了isExist()函数,并在else块做了修改。
代码如下:
public class allArray {
public static int num = 0;//计数器
/*
* Array实现无重复字符的数组的全排列 list是字符数组,i是指示当前位置的游标,length是数组长度
* 注释:这个函数最核心的地方,我感觉是else块的代码
*/
public void Array(char list[], int i, int length) {
if (i == length - 1) {
for (int j = 0; j < length; j++) {
num++;
System.out.print(list[j]);
}
System.out.println(num/length);
} else {
for (int j = i; j < length; j++) {
swap(list, i, j);// 交换当前值和当前位置之后的值
Array(list, i + 1, length);// 当前位置+1,递归
swap(list, i, j);// 再交换
}
}
}
/*
* swap实现了数组中两个位置的值的交换 list是字符数组,i,j表示要交换的位置
*/
public void swap(char list[], int i, int j) {
char temp = list[i];
list[i] = list[j];
list[j] = temp;
}
public static void main(String[] args) {
char a[] = { 'a', 'b', 'c', 'd','e','f'};// 以这个字符数组为例
allArray array = new allArray();
array.Array(a, 0, a.length);
}
}