動的計画法と再帰の概要

再帰には、再帰回帰が含まれます

再帰の例:フィボナッチ数列

#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;
}

 上記の再帰コードは古典的な再帰書き込み方法であり、コードの実行結果は次のとおりです。

 

 

 ただし、nが50または100に入ると、再帰プログラムが同じ結果の多くを繰り返し計算するため、プログラムが長時間実行される可能性があります。興味のある読者は自分でそれを試すことができます。では、フィボナッチ数列のn番目の項を計算する時間を短縮する方法はありますか?

答えはもちろんはいです。次のコードを参照してください。コードのアイデアは動的計画法です

#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;
}

 したがって、フィボナッチ数列の100番目の項目を出力してみることができます

 

 

知識のポイント:

* aはc言語のポインタを表します。これはメモリ空間を意味し、new int()はint型データに入れることができるメモリ空間を指します。

int n;

cin >> n;

int * a = new int [n]; //動的配列を定義する方法 

 

おすすめ

転載: blog.csdn.net/smallrain6/article/details/106029294