原文:https://blog.csdn.net/iloveyougirls/article/details/55044401
一、对于不重复数字的全排列(例如:1,2,3,4,5,7,8,9)
1.用数学的方法来算很简单,排列的结果是9!种情况;
下面是简单的一个代码的例子:
- public class Main {
- static int count = 0;
- public static void main(String[] args) {
- int[] a = {1,2,3};
- test(a,0);
- System.out.println(count);
- }
- public static void test(int[] a,int b){
- if(b>=a.length){
- count++;
- System.out.println(java.util.Arrays.toString(a));
- }
- for (int i = b; i < a.length; i++) {
- {int k = a[b];a[b] = a[i];a[i] = k;}
- test(a,b+1);
- {int k = a[b];a[b] = a[i];a[i] = k;}
- }
- }
- }
输出结果:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
6
二、有些时候,有重复的数字进行排列组合(例如:1,2,2)
这样的数字比较少的,很简单一眼就能看得出有3种情况的排列;
把上面的代码稍做判断就可以的到重复数字的全排列:
- public class Main {
- static int count = 0;
- public static void main(String[] args) {
- int[] a = {1,2,2};
- test(a,0);
- System.out.println(count);
- }
- public static void test(int[] a,int b){
- if(b>=a.length){
- count++;
- System.out.println(java.util.Arrays.toString(a));
- }
- for (int i = b; i < a.length; i++) {
- if(!is(a,b,i)) continue;
- {int k = a[b];
- a[b] = a[i];
- a[i] = k;}
- test(a,b+1);
- {int k = a[b];
- a[b] = a[i];
- a[i] = k;}
- }
- }
-
- public static boolean is(int[] a,int b,int i){
- for (int j = b; j < i; j++) {
- if(a[i]==a[j]){
- return false;
- }
- }
- return true;
- }
- }
输出结果:
[1, 2, 2]
[2, 1, 2]
[2, 2, 1]
3