版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
常用的有:
递归法,O(2^n),大量重复的计算
动态规划法,O(n),下面的代码用这种
矩阵运算法,O(logn), 不太常用
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int Fibonacci(int n) {
vector<int> dp=vector<int>(n+1,0);
dp[0]=0;
dp[1]=1;
for(int i=2;i<=n;i++) {
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
};
int main()
{
Solution sol;
int res=sol.Fibonacci(5);
cout<<res<<endl;
system("pause");
return 0;
}