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: