标签:style blog http io ar color os sp for
题目:给定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; }
输出:
文/闫鑫原创 转载请注明出处http://blog.csdn.net/yxstars/article/details/41516105
标签:style blog http io ar color os sp for
原文地址:http://blog.csdn.net/yxstars/article/details/41516105