Self-written C ++ code for combination issues, implemented using the divide and conquer Recursion Method

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.