Solution to an algorithm problem in a set

Source: Internet
Author: User

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;
}

Related Article

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.