如何输出一组数字,如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); } } } }
原文:https://www.cnblogs.com/w-Lou/p/14943263.html