题目:给定1-n数字,排列组合。
解法:递归。第一个数字有n种选择,第二个数字有n-1种选择,依次递归排列输出。用数组表示n个数字,用过的数字置0。
实现语言:C++
#include <iostream> using namespace std; /************************************************************************/ /* num : 需要排列的数组 count : 数组总数 numC: 已经排列的数组 iUse:已经排列的个数 iNull:置0的个数 sum: 总排列数 */ /************************************************************************/ template <class T> void ComBineNum(T *num, const int count, T *numC, int iUse, int* sum) { int iNull = 0; T *newNum = new T[count]; for (int i = 0; i < count; ++i){ memcpy(newNum, num, count); if (newNum[i] == 0){ ++iNull; if (iNull == count){ for (int i = 0; i < count; ++i){ cout << numC[i]; } cout << endl; ++(*sum); return; } continue; } numC[count - iUse] = newNum[i]; newNum[i] = 0; ComBineNum(newNum, count, numC, iUse - 1, sum); } delete[] newNum; } int main() { int sum = 0; const int count = 4; char num[count], pNum[count]; for (int i = 0; i < count; ++i){ num[i] = i + '1'; } ComBineNum<char>(num, count, pNum, count, &sum); cout << "sum :" << sum << endl; sum = 1; for (int i = 1; i <= count; ++i){ sum *= i; } cout << "sum :" << sum << endl; return 0; }
输出:
template <class T> void Swap(T& a, T& b) { T c = a; a = b; b = c; } template <class T> void Perm(T list[], int k, int m, int* count) { if (k == m){ for (int i = 0; i < m; ++ i){ cout << list[i]; } cout << endl; ++(*count); } else{ for (int i = k; i < m; ++i){ Swap(list[k], list[i]); Perm(list, k + 1, m, count); Swap(list[i], list[k]); } } } int main() { const int m = 4; int count = 0; int list[m]; for (int i = 0; i < m; ++i){ list[i] = i + 1; } Perm(list, 0, m, &count); cout << count; return 0; }