法一:递归(超时)
class Solution {
public:
int Fibonacci(int n) {
if(n <=1 ) return n;
return Fibonacci(n-1) + Fibonacci(n-2);
}
};
法二:存储计算过的每一个fibo
class Solution {
public:
int Fibonacci(int n) {
int fibo[40];
fibo[0] = 0;
fibo[1] = 1;
for(int i = 2;i<=n;i++){
fibo[i] = fibo[i-1] +fibo[i-2];
}
return fibo[n];
}
};
法三:对法二的优化
不用存储整个fibo数列,因为计算新的数列元素每次只涉及两个元素。
- sum 存储第 n 项的值
- one 存储第 n-1 项的值
- two 存储第 n-2 项的值
-
public class Solution { public int Fibonacci(int n) { if(n == 0){ return 0; }else if(n == 1){ return 1; } int sum = 0; int two = 0; int one = 1; for(int i=2;i<=n;i++){ sum = two + one; two = one; one = sum; } return sum; } }
对上述算法再次优化:只用sum,one两个变量。
public class Solution {
public int Fibonacci(int n) {
if(n == 0){
return 0;
}else if(n == 1){
return 1;
}
int sum = 1;
int one = 0;
for(int i=2;i<=n;i++){
sum = sum + one;
one = sum - one;
}
return sum;
}
}