(DP)斐波那契数列的动态规划求解(Fibonacci Dynamic Programming)

对于斐波那契数列的求解,已经有成型的递归公式,因此最简单的求解方式就是利用递归求解,但是对于庞大的数据量,显然递归的时间耗费是巨大的。

因为每次计算一个F[n]都会计算F[n-1]和F[n-2],而F[n-1]和F[n-2]的下一个子问题有很多的相同项,这无疑就有了递归过程中的重复项。

代码中设置了f[n]数组,用于保存每一级的运算结果,即对于任意一个f[n]只需要计算一次即可,大大减少了重复运算。

因此算法的时间复杂度为O(n);

//斐波那契数列的递归 动态规划解法
/*F(n)=F(n-1)+F(n-2) 
  while n>2  else F(n)=1 */
 
#include<iostream> 
#include<vector>
int n;                //the goal of the scale
std::vector<int> f;

void getScale()
{
	std::cout<<"please enter the scale of the question:";
	std::cin>>n;	
	f.push_back(1);     //begin with the index of i=0
	f.push_back(1);
	for(int i=2;i<=n;i++)
	f.push_back(0);
}

//define the function of recursion
int Fibonacci(int n)
{
	if (n<=1) return 1;
	if (f[n]!=0) return f[n];
	else return f[n]=(Fibonacci(n-1)+Fibonacci(n-2));
}


int main()
{
	getScale();
	std::cout<<Fibonacci(n);
}

如有错误和可以改进的地方,欢迎私信交流

猜你喜欢

转载自blog.csdn.net/C_acgl/article/details/79487225
今日推荐