Use C ++ to obtain all the combinations of integer 1-N ranges and N.

Source: Internet
Author: User

Problem: Locate the integer 1 ~ The N range is all sets of N, and the number in the set cannot be repeated.

The solution code is as follows:

# Include "stdafx. h"

Include <iostream>

Using namespace std;

Void PrintResult (int * log, int index)
{
For (int I = 0; I <index; ++ I)
{
Cout <log [I] <"";
}
Cout <endl;
}

Void CalCombination (int * log, int startNum, int N, int & index)
{
If (N = 0)
{
PrintResult (log, index );
}

Else
{
For (int I = startNum; I & lt; = N; ++ I)
    {
Log [index ++] = I;
CalCombination (log, I + 1, N-I, index );
    }
}
Index --;

}

Int _ tmain (int argc, _ TCHAR argv [])
{
Cout <"enter N :";
Int N = 20;
Cin> N;
Int log = new int [N];
Int index = 0;
CalCombination (log, 1, N, index );
}


It would be easy to allow repetition. Replace this sentence in recursion:

CalCombination (log, I, N-I, index );

Similarly, it can also solve the problem of having an array similar to the given element combination with a sum of N. Now we only need to sort the elements in order, and then the idea is the same.

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.