Question: Find the nth number in the Fibonacci sequence.
The so-called Fibonacci sequence refers to: The first 2 numbers are 0 and 1. The number of i-1 and the number of i-2.
The first 10 numbers of the Fibonacci series are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Answer:
(i) Recursive implementation:
Class Solution {
/**
* @param n:an integer
* @return an integer f (n) */public
int Fibonacci (int n) {
if (n==1) {return
0;
} else if (n==2) {return
1;
}
else {return
Fibonacci (n-1) +fibonacci (n-2);
}}} Total time consuming: 4634 ms
(ii) Non-recursive implementation
Class Solution {
/**
* @param n:an integer
* @return an integer f (n) */public
int Fibonacci (int n) {
int before=0,behind=0;
int result=0;
for (int i=0;i<n;i++) {
if (i==0) {
result=0;
before=0;
behind=0;
}
else if (i==1) {
result=1;
before=0;
Behind=result;
} else{
Result=before+behind;
Before=behind;
Behind=result
}
}
return result;
}
Total time consuming: 1389 ms
We see that the method of non recursion is obviously optimized and the time is reduced.