全排列算法实现

今天跟同事讨论到全排列算法,即n个数任意排列,但不能有重复的数,将所有的排列列出。

 

#include "stdafx.h" #include <iostream> #include <vector> using namespace std; template<class T> void swap(T *a, T *b) { T t = *a; *a = *b; *b = t; } template<class T> void Permutation(vector<T> &data, typename vector<T>::size_type start, typename vector<T>::size_type length) { // The base condition, that is we reach the last data. // So we print out the the current permulation. if (1 == length) { Print(data); } else { // Print out the permulation befor swaping with its next ones. Permutation(data, start + 1, length - 1); // Swaping through from the next to the last one. for (typename vector<T>::size_type i = 1; i < length; i++) { swap(&data[start], &data[start + i]); Permutation(data, start + 1, length - 1); // Swap back to keep the data order for its out caller. swap(&data[start + i], &data[start]); } } } static long nNum; template<class T> void Print(const vector<T> &data) { // Why the following block can not be compiled successfully under VS 2005. /*for (typename vector<T>::iterator it = data.begin(); it != data.end(); it++) { cout << *it; }*/ for (typename vector<T>::size_type i = 0; i < data.size(); i++) { cout << data[i]; } cout << endl; nNum++; } int _tmain(int argc, _TCHAR* argv[]) { vector<char> data; data.push_back('a'); data.push_back('b'); data.push_back('c'); data.push_back('d'); Permutation(data, 0, data.size()); cout << nNum << endl; int wait; cin >> wait; return 0; } #if 0 void permutation(char data[], long start, long len) { // The base condition, that is we reach the last data. // So we print out the the current permulation. if (1 == len) { printf("%s", data); printf("/n"); } else { // Print out the permulation befor swaping with its next one. permutation(data, start + 1, len - 1); // Swaping through from the next to the last one. for (long i = 1; i < len; i++) { swap(data[start], data[start + i]); permutation(data, start + 1, len - 1); // Swap back to keep the data order for it out caller. swap(data[start + i], data[start]); } } } int _tmain(int argc, _TCHAR* argv[]) { char data[] = "abc"; permutation(data, 0, 3); int wait; cin >> wait; return 0; } #endif

参考文章:http://www.cnblogs.com/nokiaguy/archive/2008/05/11/1191914.html

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(全排列算法实现)