In qszhoufuge, we can see the following questions about an algorithm problem with a set:
Design an algorithm to solve all combinations of k (k <= n) elements selected from the set {1 .. n. For example, the output result of Selecting All the combinations of two elements from the set {1 .. 4} is: 1, 1, 2 3, 2 4.
When I was at home in the morning, I wrote my hand and solved it cyclically. Because there was no environment test, I found an error in the test at some time in the afternoon. Haha. Sorry.
Later, I thought it was not difficult to solve this problem. recursion can solve this problem well. As a result, I had to calm down and think about it. Actually, Recursive Implementation is not complicated. This time, I finally passed it all at once. ^ _ ^
The implementation algorithm is as follows (tested ):
# Include <stdio. h>
// Display combination
// NCount: number of combinations
// P: array pointer
Inline void p2s (int nCount, int * p)
{
For (int I = 0; I <nCount; ++ I)
{
Printf ("/t % d", * (p + I ));
}
Printf ("/r/n ");
}
// Recursive combination
// NStart start count
// NMax: Maximum Value
// NCount: number of combinations
// NIndex: Composite Index (number of the combination, starting from 0)
// P: array pointer
Void func0 (int nStart, int nMax, int nCount, int nIndex, int * p)
{
For (int I = nStart; I <nMax-nCount + nIndex + 2; I ++)
{
* (P + nIndex) = I;
If (nCount-1 = nIndex)
{
P2s (nCount, p );
}
Else
{
Func0 (I + 1, nMax, nCount, nIndex + 1, p );
}
}
}
// Combined algorithm
// N: range: 1 ~ N
// NCount: number of combinations
Void func (int n, int k)
{
Int * p = new int [k];
Func0 (1, n, k, 0, p );
}
Int _ tmain (int argc, _ TCHAR * argv [])
{
Func (4, 2 );
Getchar (); // wait for exit
Return 0;
}