Algorithm: C ++ permutation and combination
Question: give 1-N numbers and arrange and combine them.
Solution: recursion. The first number has n options, the second number has n-1 options, and the output is recursively arranged. Use an array to represent n numbers, and set the number used to 0.
Implementation language: C ++
# Include
Using namespace std; /*************************************** * ******************************** // * num: count: Total number of arrays numC: List of sorted arrays iUse: Number of sorted iNull: Number of 0 set sum: total number of permutation *//********************************** * ***********************************/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 ;}
Output:
Text/Xin Xinyuan ChongReprinted please indicate the source http://blog.csdn.net/yxstars/article/details/41516105