1. 程式人生 > 其它 >java 使用遞迴實現陣列的全排列

java 使用遞迴實現陣列的全排列

如何輸出一組數字,如1.2.3的全排列組合呢?

這裡使用遞迴的方法實現,對陣列各層進行交換(每層的第一個數與陣列的其他數字進行交換,我們根據第一個數的不同,即可斷定它們不是同一序列)

public class test3 {
public static void main(String[] args) {
int a[] = {1,2,3};
//swap(a,0,1);
// System.out.println(Arrays.toString(a));
pailie(a,0,2);
}

//完成陣列指定位置的交換
static void swap(int b[],int x,int y){
int temp = b[x];
b[x] = b [y];
b[y] = temp;
}

//進行分層的全排列
static void pailie(int c[],int cursor,int end){
//當執行道最後一層時,所有分層排序情況都已完成,對最終交換陣列進行輸出
if (cursor==end){
System.out.println(Arrays.toString(c));
}else {
for (int i=cursor;i<=end;++i){
swap(c,cursor,i);
pailie(c,cursor+1,end);
//此處需要將陣列的排序恢復,以保證與原來的序列一致,使我們能夠遍歷完全所有情況
swap(c,cursor,i);
}
}
}
}