Brief description of dynamic programming

The Fibonacci sequence is colorful, expressed by a simple mathematical formula
F(n)=(n<=2)
F(n)=F(n-1)+F(n-2)(n>2)
The procedure is as follows

int Fibonacci (int n)
{
    
    
  if (n<=2)
  {
    
    
    return 1;
  }
  else
  {
    
    
    return Fibonacci(n-1)+Fibonacci(n-2);
  }
}

But when n becomes very large, the recursive call will increase exponentially. Therefore, when implementing the Fibonacci algorithm, we can try to think about the use of for or while instead? Will it be more efficient?

int Fibonacci (int n)
{
    
    
int vis1=1;//保存Fibonacci(n-1)的值
int vis2=1;//保存Fibonacci(n-2)的值
int result;//保存Fibonacci(n-1)+Fibonacci(n-2)的值
 if(n<=2return 1;
 for(int i=2;i<n;i++)
 {
    
    
    result=vis1+vis2;
    vis2=vis1;
    vis1=result;
 }
 return result;
}

When n is large enough, the performance of this algorithm will far exceed the first (recursive).
This whole process seems simple, but in the actual operation process will encounter many problems, which we still need a lot of practice and learning.

Guess you like

Origin blog.csdn.net/qq_45531709/article/details/108028750