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.