全排列 最详细的解题报告

题目大意:求任意集合的全排列

解题思路:假设数据存放在数组array[0,1...,length-1]中,首先固定下标为first=0的数,计算array[1,...,length-1]的全排列,依次类推,当first==length-1是,输出数组中的数据。当计算完array[1,...,length-1]的全排列后(此时first=0),然后需要将下标为1,...,length-1的所有数与first进行交换,即array中的每一个数都要放在first=0的位置,然后再依次类推。

 

具体算法(java版)

 1 //将array数组中下标为m和n的数据进行交换
 2     public static void swap(int[] array, int m, int n) {
 3         int x = array[m];
 4         array[m] = array[n];
 5         array[n] = x;
 6     }
 7 
 8     //输出array数组中的数据
 9     public static void output(int[] array) {
10         for (int i = 0; i < array.length; i++) {
11             System.out.print(array[i] + "\t");
12         }
13         System.out.println();
14     }
15 
16     public static void permutation(int[] array, int first) {
17         if (first == array.length - 1) {// first已经到最后一个元素了,即所有的元素都已经固定了
18             output(array); 
19         } else {
20             for (int i = first; i < array.length; i++) {
21                 swap(array, i, first); //交换
22                 permutation(array, first + 1); //first以前的元素都固定了,接下来固定first+1
23                 swap(array, i, first); //还原
24             }
25         }
26     }
27 
28     public static void main(String[] args) {
29         int[] array = { 1, 2, 3 }; // 待排列的元素
30         permutation(array, 0);
31     }

 

posted @ 2014-10-23 11:37  PinXiong  阅读(254)  评论(0编辑  收藏  举报