題目:給定1-n數字,排列組合。
解法:遞歸。第一個數字有n種選擇,第二個數字有n-1種選擇,依次遞歸排列輸出。用數組表示n個數字,用過的數字置0。
實現語言:C++
#includeusing namespace std; /************************************************************************/ /* num : 需要排列的數組 count : 數組總數 numC: 已經排列的數組 iUse:已經排列的個數 iNull:置0的個數 sum: 總排列數 */ /************************************************************************/ template 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 (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