Introduction to dynamic programming and recursion

Recursion includes recursion and regression

Recursion example: Fibonacci sequence

#include<iostream>
#include<ctime>
using namespace std;

int fibo(int n)
{
    if (n < 1) return -1;
    else if (n == 1 || n == 2) return 1;
    else if (n > 2) return fibo(n -1) + fibo(n - 2);
}
int main()
{
    int start_time,end_time,total_time;
    int n;
    cin >> n;
    //记录程序开始时间
    start_time = clock();
    cout << fibo(n) << endl;
    //记录程序结束时间
    end_time = clock();
    total_time = end_time - start_time;
    cout << total_time << endl;
    return 0;
}

 The above recursive code is a classic recursive writing method, the code execution results are as follows:

 

 

 However, when n enters 50 or 100, the program may execute for a long time, because the recursive program repeatedly calculates many of the same results. Interested readers can try it by themselves. So is there a way to reduce the time to calculate the nth term of the Fibonacci sequence?

The answer is of course yes, refer to the following code, the code idea is dynamic programming :

#include<iostream>
#include<ctime>
#include<iomanip>
using namespace std;

long double fibo2(int n)
{
    long double temp;
    if (n < 1) return -1;
    long double *a = new long double[n + 1];//定义一个长度为n + 1的动态数组
    a[1] = a[2] = 1;
    for (int i = 3;i <= n;i++)
    {
        a[i] = a[i - 1] + a[i - 2];
    }
    temp = a[n];//将Fibonacci数列的第n项存在一个变量之中
    delete []a; //删除定义的数组
    return temp;
}
int main()
{
    int start_time,end_time,total_time;
    int n;
    cin >> n;
    start_time = clock();                    //记录程序开始时间
    cout << fixed << setprecision(0);        //输出格式不使用科学计数法
    cout << fibo2(n) << endl;                //执行递归程序
    end_time = clock();                      //记录程序结束时间
    total_time = end_time - start_time;
    cout << total_time << endl;
    return 0;
}

 So you can try to output the 100th item of the Fibonacci sequence

 

 

Knowledge points:

*a represents the pointer in the c language, which means a memory space, new int() refers to the memory space that can be put into int type data

int n;

cin >> n;

int *a = new int [n];//Method of defining dynamic array 

 

Guess you like

Origin blog.csdn.net/smallrain6/article/details/106029294