来源:http://blog.csdn.net/e3399/article/details/7543861
(一)递归的全排列算法
(A、B、C、D)的全排列为
1、A后面跟(B、C、D)的全排列
2、B后面跟(A、C、D)的全排列
3、C后面跟(A、B、D)的全排列
4、D后面跟(A、B、C)的全排列
而对1中的(B、C、D)照样可以按照上面的形式进行分解。
1 /********************************************************************** 2 * Compiler: GCC 3 * Last Update: Mon 07 May 2012 07:08:58 PM CST 4 * File Name: 1.cpp 5 * Description: 利用stl中的next_permutation进行全排列 6 ************************************************************************/ 7 #include <iostream> 8 using namespace std; 9 10 template<typename T> 11 void permutation(T array[], int begin, int end) 12 { 13 int i; 14 15 if(begin == end){ 16 for(i = 0; i <= end; ++i){ 17 cout<<array[i]<<" "; 18 } 19 cout<<endl; 20 return; 21 } else { 22 //for循环遍历该排列中第一个位置的所有可能情况 23 for(i = begin; i <= end; ++i) { 24 swap(array[i], array[begin]); 25 permutation(array, begin + 1, end); 26 swap(array[i], array[begin]); 27 } 28 } 29 } 30 31 int main(int argc, char **argv) 32 { 33 int a[4] = {1, 2, 3, 4}; 34 permutation(a, 0, sizeof(a) / sizeof(int) - 1); 35 36 return 0; 37 }