代码如下:
1 /** 2 * 3 * 递归求数组的全排列:第一个位置有n种选择,第二个位置有n-2+1种选择,第k个位置有n-k+1中选择。 4 */ 5 private static List<int[]> notEqualSeries2(int n ,int[] result , int index ,List<int[]> list) { 6 //得到第k层的可能选择queue 7 Queue<Integer> queue = new ArrayDeque<Integer>(n-index); 8 for (int i = 1; i <= n; i++) { 9 boolean flag=false; 10 for (int j = 0; j < index; j++) { 11 12 if (result[j]==i) { 13 flag=true; 14 break; 15 } 16 } 17 if (!flag) { 18 queue.add(i); 19 } 20 } 21 // Queue<Integer> queue = new ArrayDeque<Integer>(n); 22 // for (int i = 1; i <= n; i++) { 23 // queue.add(i); 24 // } 25 // for (int i = 0; i < index; i++) { 26 // queue.remove(result[i]); 27 // } 28 29 int size=queue.size(); 30 //依次出队列完成一次选择 31 for (int i = 0; i < size; i++) { 32 result[index]=queue.remove(); 33 if (index==n-1) { 34 //最后一层 35 list.add(result.clone()); 36 continue; 37 } 38 //递归求解 39 notEqualSeries2(n, result, index+1, list); 40 41 } 42 return list; 43 }
另外一种方法:就在一个数组上完成所有的排列,极大的节省空间
1 //求数组数组成的全排列 2 //第k位置上的数m,m依次出现在k,K+1,K+2...... 位置上,递归处理到最后位置上时,得到一个排列,当按此规矩循环完所有数和位置时 ,得到目标全排列 3 private static List<int[]> getSeries2(int[] arr , int index ,List<int[]> list) { 4 //递归到最后位置时完成依次排列 5 if (index==arr.length-1) { 6 list.add(arr.clone()); 7 return list; 8 9 }else { 10 for(int i=index;i<arr.length;i++){ 11 //以交换的方式实现m依次出现在k,k+1,k+2......上 12 swapArr(arr, index, i); 13 //递归处理 14 getSeries2(arr, index+1, list); 15 //恢复现场(m交换到一个位置后,递归处理得到排列后,回退到这层时先恢复原位置,以便其交换到另一个位置(i++)) 16 swapArr(arr, index, i); 17 } 18 } 19 20 return list; 21 } 22 private static int[] swapArr(int[] arr ,int x,int y) { 23 int temp=arr[x]; 24 arr[x]=arr[y]; 25 arr[y]=temp; 26 return arr; 27 }
浙公网安备 33010602011771号