一种网上流传的递归型全排列算法,原创不详。只不知如果数组中有重复的元素的话何解?
#include <iostream> void permutation(char* list, int begin, int end) { if(begin < end) { for(int i = begin; i <= end; ++i) { std::swap(list[i], list[begin]); permutation(list, begin + 1, end); std::swap(list[i], list[begin]); } } else { for(int i = 0; i <= end; ++i){ std::cout << list[i]; } std::cout << std::endl; } } int main() { char a[] = "1234"; std::cout << a << "的全排列结果如下:" << std::endl; permutation(a, 0, (int)strlen(a) - 1); return 0; }
在http://blog.csdn.net/hackbuteer1/article/details/6657435看到STL的思路实现的全排列
STL有一个函数next_permutation(),它的作用是如果对于一个序列,存在按照字典排序后这个排列的下一个排列,那么就返回true且产生这个排列,否则返回false。注意,为了产生全排列,这个序列要是有序的,也就是说要调用一次sort。
#include <iostream> #include <algorithm> void permutation(char* list, int length) { std::sort(list, list + length); do { for(int i = 0; i < length; ++i) { std::cout << list[i]; } std::cout << std::endl; }while(std::next_permutation(list, list + length)); } int main() { char a[] = "1234"; std::cout << a << "的全排列结果如下:" << std::endl; permutation(a, (int)strlen(a)); return 0; }
由全排列算法联想到一个经典问题:八皇后问题
/* ----- eight queen ----- */ #include <iostream> #include <algorithm> int g_number = 0; void printQueen(int list[], int length) { printf("queenList[%d]:\t", g_number); for (int i = 0; i < length; ++i) { printf("%d ", list[i]); } printf("\r\n"); } bool check(int list[], int length) { for (int i = 0; i < length; ++i) { for (int j = i + 1; j < length; ++j) { if ( (i - j == list[i] - list[j]) || (i - j == list[j] - list[i]) ) { return false; } } } return true; } void permutation(int ColumnIndex[], int index, int length) { if (index == length) { if(check(ColumnIndex, length)) { ++g_number; printQueen(ColumnIndex, length); } } else { for(int i = index; i < length; ++ i) { std::swap(ColumnIndex[i], ColumnIndex[index]); permutation(ColumnIndex, index + 1, length); std::swap(ColumnIndex[i], ColumnIndex[index]); } } } void eightQueen() { const int queenCount = 8; int queenList[queenCount]; for (int i = 0; i < queenCount; ++i) { queenList[i] = i; } permutation(queenList, 0, queenCount); } int main(int argc, char const *argv[]) { eightQueen(); return 0; }