递归算法——全排列

来源:互联网 发布:mac无法更新软件 编辑:程序博客网 时间:2024/06/05 16:01
#include <iostream>#include <fstream>using namespace std;int n = 0;ofstream fout("perm.txt");void swap(int *a, int *b){int tmp = *a;*a = *b;*b = tmp;}bool contains(int list[], int k, int i){for (int j = k; j < i; j++){if (list[j] == list[i])return true;}return false;}void perm(int list[], int k, int m){if (k == m){for (int i = 0; i <= m; i++)fout << list[i] << " ";fout << endl;n++;}else{for (int i = k; i <= m; i++){if (!contains(list, k, i)){swap(&list[k], &list[i]);perm(list, k + 1, m);swap(&list[k], &list[i]);}}}}int _tmain(int argc, _TCHAR* argv[]){int list[] = {8, 2, 3, 4, 5, 6, 7, 8};perm(list, 0, 7);fout << "total number of solution is " << n << endl;fout.close();cout << "Done!" << endl;return 0;}