//个人ac
class Solution {
public:
int Fibonacci(int n) {
if(n==0){
return n;
}else if(n==1||n==2){
return 1;
}else{
int a=1;
int a2=1;
int sum=0;
for(int i=3;i<=n;i++){
sum=a+a2;
a=a2;
a2=sum;
}
return sum;
}
}
};
方法一:
递归
int Fibonacci(int n) {
if (n==0 || n==1) return n;
return Fibonacci(n-1) + Fibonacci(n-2);
}
方法二:
动态规划
int Fibonacci(int n) {
vector<int> dp(n+1, 0);
dp[1] = 1;
for (int i=2; i<=n; ++i) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
int Fibonacci(int n) {
if (n == 0 || n == 1) return n;
int a = 0, b = 1, c;
for (int i=2; i<=n; ++i) {
c = a + b;
a = b;
b = c;
}
return c;
}