一、对于不重复数字的全排列(例如: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种情况的排列;