有A,B,C, D四个数,求他们的全排列:
首先选取第一位,有四种情况
A B C D
B A C D
C B A D
D B C A
对于剩下的三个数字,用同样的方法,先确定第一个数字即可。以BCD为例,有
B C D
C B D
D B C
.....
1.从N个数中取出N个进行全排列
Java版代码:
public class Permutations { public static void main(String[] args) { String s = "abcd"; permutations(s); } // 全排列 public static void permutations(String s) { char[] arr = s.toCharArray(); int[] cnt = new int[1]; _permutations(arr, 0, cnt); System.out.println("共有" + cnt[0] + "中排列"); } // cnt 用来统计排列的个数 private static void _permutations(char[] arr, int start, int[] cnt) { if (start == arr.length - 1) { cnt[0]++; System.out.println(arr);
return; } char tmp; for (int i = start; i < arr.length; ++i) { tmp = arr[start]; arr[start] = arr[i]; arr[i] = tmp; _permutations(arr, start + 1, cnt); tmp = arr[start]; arr[start] = arr[i]; arr[i] = tmp; } } }
效果:
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
共有24中排列
2.从N个数中取出M个进行全排列
public class Permutations { public static void main(String[] args) { String s = "abcd"; permutations(s, 2); } public static void permutations(String s, int num) { char[] arr = s.toCharArray(); int[] cnt = new int[1]; // 异常处理 if (num <= 0 || num > arr.length) num = arr.length; _permutations(arr, 0, num, num, cnt); System.out.println("共有" + cnt[0] + "中排列"); } // num表示对M个数进行全排列,leftNum记录剩余要排列的个数 private static void _permutations(char[] arr, int start, int num, int leftNum, int[] cnt) { if (leftNum == 0) { for (int i = 0; i < num; ++i) { System.out.print(arr[i]); } System.out.println(); cnt[0]++;
return; } char tmp; for (int i = start; i < arr.length; ++i) { tmp = arr[start]; arr[start] = arr[i]; arr[i] = tmp; _permutations(arr, start + 1, num, leftNum-1, cnt); tmp = arr[start]; arr[start] = arr[i]; arr[i] = tmp; } } }
效果:
ab
ac
ad
ba
bc
bd
cb
ca
cd
db
dc
da
共有12中排列