Programmer interview question selection (44): integer segmentation (that is, all combinations of a number N from the sum of numbers less than or equal to N)

Source: Internet
Author: User

Question Description: for example, given an integer 4, it has the following situation: 4 = 4;

4 = 3 + 1;

4 = 2 + 2;

4 = 2 + 1 + 1;

4 = 1 + 1 + 1 + 1;

The following is the split implementation code of the two versions.

# Include "stdio. H"

Int compute (INT number, int maximum)
{
If (number = 1 | maximum = 1)
Return 1;
Else if (number <maximum)
Return compute (number, number );
Else if (number = maximum)
Return 1 + compute (number, maximum-1 );
Else
Return compute (number, maximum-1) + compute (number-maximum, maximum );
}
 
Int intpartionno (int n) // calculates the total number of versions of the combination;
{
Return compute (N, N );
}

Int integerpartition (int n) // calculates the total number of combinations and prints out all versions;
{
Int * partition = new int [N] ();
Int * repeat = new int [N] ();

Partition [1] = N;
Repeat [1] = 1;
Int COUNT = 1;
Int part = 1;

Int last, smaller, remainder;

Printf ("% 3d", partition [1]);
Do
{
Last = (partition [Part] = 1 )? (Repeat [part --] + 1): 1;
Smaller = partition [Part]-1;
If (Repeat [Part]! = 1)
-- Repeat [Part ++];
Partition [Part] = smaller;
Repeat [Part] = 1 + last/smaller;

If (remainder = last % smaller )! = 0)
{
Partition [++ part] = remainder;
Repeat [Part] = 1;
}

++ Count;

Printf ("/N ");
For (INT I = 1; I <= part; ++ I)
For (Int J = 1; j <= repeat [I]; ++ J)
Printf ("% 3d", partition [I]);

} While (Repeat [Part]! = N );

If (partition)
{
Delete [] partition;
Partition = 0;
}
If (Repeat)
{
Delete [] Repeat;
Repeat = 0;
}

Return count;
}

Int main ()
{
Printf ("% d/N", intpartionno (4 ));
Integerpartition (4 );
Getchar ();
}

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.