Split the integer nSum into the sum of the number of num-Alibaba pen exam

Source: Internet
Author: User

An integer nsum is decomposed into num integers and forms. For example, if nsum = 6, num = 3, nsum can be decomposed into 1.
1 4; 1 2 3; 222. Please program it!

 

Method resolution: recursive algorithms are used. during decomposition, the value of each layer (nDepth, based on 0) is no smaller than that of the previous layer, therefore, the variable I in the loop body should start from the value of the previous layer until nSum/num expires, because the maximum value of the last group should be nSum/num. The value of nDepth + num is the total number of splits.

 

The Code is as follows:

# Include <iostream> using namespace std; //////////////////////////////////////// /// // nSum: parameters to be split; // num: Number of shards to be split in the current recursive layer // pData: stores each shard unit // nDepth: depth of the shard (based on 0) // num + nDepth: sum of the total number of final splits /////////////////////////// //// // void SegNum (int nSum, int num, int * pData, int nDepth) {if (1 = num) {pData [nDepth] = nSum; for (int j = 0; j <num + nDepth; j ++) cout <pData [j] <""; co Ut <endl;} else {// If the depth is 0, then I starts indexing from 1; // otherwise, I starts indexing from the value corresponding to the previous depth. Int I = (nDepth = 0? 1: pData [nDepth-1]); // The maximum I value is nSum/numfor (; I <= nSum/num; I ++) {pData [nDepth + +] = I; segNum (nSum-I, num-1, pData, nDepth); nDepth --;}}}

The test code is as follows:

int main(){int nSum = 10;int num = 3;cout << "nSum = " << nSum << endl;cout << "num = " << num << endl;int* pData = new int[num];SegNum(nSum, num, pData, 0);if (pData!=NULL){delete pData;pData=NULL;}system("pause");}

The test results are as follows:


 

 

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.