偶尔刷题,经常遇到需要全排列的地方,一直想用for循环做(n层),理论上是可行的,,可是实际(两三层还行,十层八层,n层,不太合适吧),再次重温一下全排列算法。
【1】案例分析
【百度百科】:从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
a,b,c,d的全排列如下(程序生成)
a b c
a c b
b a c
b c a
c b a
c a b
【2】设计思想
采用递归的思想,,(以{“a”, “b”, “c”}为例。)
【1】由于每个元素只能使用一次,所以主要使用交换的方式。
【2】先挑选第一个位置的元素,将a和a,b,c,三个都交换一次(a和a交换保证能选择到a)
【3】挑完第一个使用递归挑选下一个,重读【2】
执行流程图如下:
【3】算法实现
package algorithm_1;
/**
* Created by zsl on 2017/8/20.
*/
public class FullPermutation {
public static int total = 0;
public static void main(String[] args) {
String str[] = {"a", "b", "c"};
arrange(str, 0, str.length);
System.out.println(total);
}
/**
* 交换str数组的 i和 j。
*
* @param str
* @param i
* @param j
*/
public static void swap(String[] str, int i, int j) {
String temp = new String();
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
/**
* 对str数组,,从st到len进行全排列
*
* @param str
* @param st
* @param len
*/
public static void arrange(String[] str, int st, int len) {
if (st == len - 1) {
for (int i = 0; i < len; i++) {
System.out.print(str[i] + " ");
}
System.out.println();
total++;
} else {
for (int i = st; i < len; i++) {
swap(str, st, i);
arrange(str, st + 1, len);
swap(str, st, i);
}
}
}
}