Algorithm Description: Select the number of m from the n number, can be decomposed into the following two steps
(1) First select the number of the maximum number from the n number, and then select the number of m-1 in the remaining number of n-1, until the number of N (m-1) is selected from 1.
(2) Select a number from the n number of minor numbers, and proceed to step (1) until the maximum number of currently selectable numbers is M.
1#include <iostream>2 3 using namespacestd;4 5 voidCombine (intA[],intNintMintB[],Const intM);6 7 intMain ()8 {9 //Choose M number from N number, n=6,m=3Ten Const intN =6; One Const intM =3; A - intA[n]; - intB[M];//used to store elements in the current composition (this is where the element subscript is stored) the for(inti =0; i < N; i++) -A[i] = i+1; - - Combine (A, N, M, B, M); + - return 0; + } A at voidCombine (intA[],intNintMintB[],Const intM) - { - for(inti = n; I >= m; i--) - { -b[m-1] = i-1;//Select the largest number in the candidate set a[] and record its subscript - if(M >1) inCombine (A, I-1, M-1, b, M);//Select M-1 elements from the n-1 - Else //1==m, there is no element optional, a combination has been completed, the output to { + for(intj = m1; J >=0; j--) -cout<<A[b[j]]; thecout<<Endl; * } $ }Panax Notoginseng}
Recursive implementation of combinatorial problems