Original title reproduction:
3 = 2 + 1 = 1 + 1 + 1 so 3 has three kinds of disassembly
4 = 3 + 1 = 2 + 2 = 2 + 1 + 1 = 1 + 1 + 1 + 1 Total Five
5 = 4 + 1 = 3 + 2 = 3 + 1 + 1 = 2 + 2 + 1 = 2 + 1 + 1 + 1 = 1 + 1 +1 +1 +1 A total of seven
And so on, what is the number of disassembly methods for a specified number num?
Programming:
1. Integer variable n is used to record the number to be determined, and the integer pointer T is used to point to a successful set of results. Integer variable i is used to control the initialization of the array loop;
2, the key algorithm recursive search results sequence dismantling;
3, Output function, Printresult.
Algorithm Description:
1, the first time to pass the number of the determination of N, the resulting sequence of results in the number of results in the array of the ordinal I, the result array t;
2, if n is 0, the output result; otherwise, the number of i+1 in the sequence of cyclic test results;
3, if the i>0 and cyclic test k is not in the result sequence before his position in the number of t[i-1] then perform 2, otherwise perform 4;
4, t[i]= K; n-= k; i++;
5, recursive judgment of the remainder of N;
6, Reverse 4, and return 2.
/* Function: Digital disassembly time: 2014-09-08 21:03:40*/#include <stdio.h> #include <malloc.h>void dismantling (int n, int i, int *t );//recursive search result sequence void printresult (int i, int *t);//print result int count = 0;int Main () {int n;//number to be determined int *t;//result sequence cache array int i;//initialize result array variable Volume printf ("Please Enter a number (n>0):"); scanf ("%d/n", &n); t = (int *) malloc (n); for (i=0; i<n; i++) {t[0] = 0;} Dismantling (n, 0, T);//free (t); return 0;} void Dismantling (int n, int i, int *t) {int k;if (n = = 0) {//output resultprintresult (I, t);} Else{//recursive Find Result sequencefor (k=1; k<=n; k++) {if (i>0 && k<t[i-1])//Let large number in, after decimal in front, Used to prevent duplicate results continue;t[i] = k;n-= k;i++;D ismantling (n, I, t); i--;n +=k;t[i] = 1;}}} void Printresult (int i, int *t) {int j;printf ("The%3d Result is:", ++count); for (j=i-1; j>0; j--) {printf ("%d+", T[j]);} printf ("%d\n", T[0]);}
Results:
Question: I just need a free (t) to appear
Do not know what the reason, hope that experts are not hesitate to enlighten.
C Language Learning--Digital disassembly