Recursive implementations are the most commonly thought-out approach, with the following code:
Recursive Way long Fibonacci (unsigned n) {if (n==0) {return 0;} else if (n==1) {return 1;} Else{return Fibonacci (n-1) +fibonacci (n-2);}}
Obviously recursion is not the best method, and when n is large, efficiency will be very low.
The good ideas are:
From the bottom up, F (2) is calculated based on F (0) and F (1), and F (2) is calculated according to F (1) and F (3). And so on, you can figure out the nth item. The time complexity of this idea is O (n).
Non-recursive Way long fibonaccitwo (unsigned n) {int result[2]={0,1};if (n<2) {return result[n];} Long F_nmisone=1;long f_nmistwo=0;long f=0;for (int i=2; i<=n; i++) {//f (n) =f (n-1) +f (n-2) f=f_nmisone+f_nmistwo;f_ Nmistwo=f_nmisone;f_nmisone=f;} return F;}
The first 21 elements of the output Fibonacci sequence are as follows:
"Sword point offer" Fibonacci sequence (recursive and non-recursive implementations)