The combination problem is a classic algorithm problem. You must extract m from n objects (characters or numbers) and list all the obtaining methods.
# Include <iostream>
Using namespace STD;
# Define maxnum100
Template <class T>
Void comp (t list [], int start, int end, int num, t result []) // from start to end of list, num combination, saved to result
{
/* If (Start> end)
{
Cout <"comp fail: Start> end! "<Endl;
Return;
}*/
/* If (Num> end-start + 1)
{
Cout <"comp fail: num <End-start + 1! "<Endl;
Return;
}*/
Static int result_index = 0;
If (result_index = num) // recursive critical condition: if the number of result elements has reached num
{
For (Int J = 0; j <num; j ++)
{
Cout <result [J] <"";
}
// Cout <"output:" <start <"" <End <Endl;
Cout <Endl;
}
Else
{
For (INT loop = 0; loop <End-start + 1; loop ++)
{
Result [result_index] = list [start + loop];
Result_index ++;
// Cout <"Enter:" <start <"" <End <Endl;
Comp (list, start + loop + 1, end, num, result );
// Cout <"Exit:" <start <"" <End <Endl;
Result_index --;
}
}
}
Void main (void)
{
Int W [] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
Int A [maxnum];
Comp (W, 0, 4, 3, );
System ("pause ");
}
Running result:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
If you are executing comp (W, 1, 5, 6, A); the running result is null, because 1 ~ 5. There are only five objects, and a combination of six objects cannot be obtained.