An old question: Divide positive integer N into the sum of several num different positive integers

Source: Internet
Author: User

/*

Http://www.newsmth.net/bbstcon.php? Board = Algorithm & gid = 33809

Sender: firebugp (Firefox), email area: Algorithm
Question: an old question
Mail station: Shui muCommunity(Tue Nov 3 00:50:48 2009), Station

Divide positive integer N into the sum of several num different positive integers and give all possible split results (numbers are the same and order is different
For example, 6 = 1 + 2 + 3 and 6 = 3 + 2 + 1 are the same thing, 6 = 2 + 4 and 6 = 1 + 5 are eligible
Results)
*/

# Include <stdio. h>
# Include <set>
# Include <vector>
# Include <algorithm>

Typedef STD: Set <int> container;
Container res;
STD: vector <container> allres;

Void printall ()
{
For (INT I = 0; I <allres. Size (); I ++)
{
For (container: iterator it = allres [I]. Begin (), end = allres [I]. End ();
It! = End; ++ it)
{
Printf ("% d", * it );
}
Printf ("\ n ");
}
}

Bool operator = (container const & A, container const & B)
{
If (A. Size ()! = B. Size ())
Return false;

For (container: const_iterator ita = A. Begin (), Enda = A. End (), ITB = B. Begin ();
Ita! = ENDA; ++ ITA, ++ ITB)
{
If (* ita! = * ITB) return false;
}

Return true;
}

Void add ()
{
If (allres. End ()! = STD: Find (allres. Begin (), allres. End (), Res ))
Return;
Allres. push_back (RES );
}

// divide positive integer N into the sum of different positive integers of num
// place the result in the global variable allres
void split (int n, int num)
{< br> If (Num * (Num + 1)/2> N) // no solution
return;
// there is only one number, ending
If (num = 1)
{< br> If (res. find (n) = res. end ()
{< br> res. insert (n);
Add ();
res. erase (n);
}< br> return;
}

// Otherwise, traverse all possible
For (INT I = 1; I <= N-(num-1) * num/2; I ++)
{
If (res. Find (I) = res. End ())
{
Res. insert (I );
// If (n-I >=( num-1) * num/2)
Split (n-I, num-1 );
Res. Erase (I );
}
}
}

Void main ()
{
Split (16, 3 );
Printall ();
}

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.