I recently saw a batch of interview questions and was interested. I had to solve the problem and practice my thinking.
Everybody's Test 1: a person can take one, two, or three steps at a time. How many steps can this person take on N layers?
Idea: first establish a mathematical model, set up three steps to go I, two steps to go j times, one step to go K times, 3 * I + 2 * j + 1 * k = n steps. taking I + J + K times in total, equals to dividing the length of n steps into I + J + k paragraphs, and then entering I 3, J 2, k 1. in this way, when divided into I + J + k paragraphs, according to the knowledge of arrangement and combination, all filling methods are (I + J + k )! /(I! * J! * K !) In the program, use the getcomb (I, j, k) function to calculate this value.
For the determination of I, J, K, we can use the large to small division, divide the number of times by 3 first, then divide the number by 2, and the rest are counted as the number of times by 1, the specific program contains the I, j, and two repeating loops.
// Auxiliary function, calculate the factorial int factorial (int n) {int ret = N; If (n <= 1) {return 1 ;}while (n --> 1) {RET * = N;} return ret;} // evaluate (I + J + k )! /(I! * J! * K !) Int getcomb (int I, Int J, int K) {int result = 1; int M = factorial (I + J + k); int L = factorial (I) * factorial (j) * factorial (k); Return M/L;} // main function int nstepfor123 (int n) {int I = 0; Int J = 0; int P; int K; int result = 0; for (I = 0; I <= N/3; I ++) {P = n-I * 3; for (j = 0; j <= p/2; j ++) {k = p-J * 2; // evaluate (I + J + k )! /(I! * J! * K !) Result + = getcomb (I, j, k) ;}} return result ;}
In addition, there is a mathematical induction method first to get the recursive formula:
F (n) = f (n-1) + f (n-2) + f (n-3), especially F (0) = 1; F (1) = 1; F (2) = 2;
The formula is as follows: when we add a common step of F (n + 1), there are three situations after we calculate this new step, 1 is that this step is only taken as F (n) Times, 2 is that this step matches the original last step as the two steps are taken as F (n-1) times, 3 is this step with the previous two steps for three steps for F (n-2); so the formula F (n + 1) = f (n) + f (n-1) + f (n-2), summed up evidence.
This method can reduce the complexity to O (n), and only the addition method is better than the first method above. To compute F (N), you only need to record the first three values for the next value. The program implementation is as follows:
int f (int k){int v[3]={1,1,2};int index = -1;int i = 0;if (k<0){return 0;}if (k<3){return v[k];}while(k-->2){index++;index %= 3;v[index] = v[0]+v[1]+v[2];}return v[index];}