Article Directory
Title Description
We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0).
n<=39
Time limit: C / C ++ 1 second, 2 seconds of space restrictions in other languages: C / C ++ 32M, 64M heat index of other languages: 726 760
this question knowledge: Recursive
Fibonacci number
Each number is the sum of the first two: 1,1,2,3,5,8,13,21,34 ...
Problem-solving ideas
This problem is relatively simple, Fibonacci number defined in the rule data from the point of view, we know that it is easy to implement a recursive:
when n> 2: Fibonacci (n) = Fibonacci (n-1) + Fibonacci (n-2 )
But we know that recursively for programmers, training requirements of various issues is extremely high, infinite recursion, stack overflow, security is also more difficult to grasp, so we should try to avoid using recursion.
Recursive efficiency issues, with particular reference to: Talk recursive: recursive efficiency
Here, we use recycled directly to achieve:
class Solution {
public:
int Fibonacci(int n) {
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
int a = 0,b = 1;//a,b是数列的前两项
int c = 0;//c是当前所求项
int i;//i用来控制循环,求得斐波那契数列的第n项
for(i = 2;i <= n;i++){
c = a + b;
a = b;
b = c;//交换变量,数列求解往后进行
}
return c;
}
};