动态规划实现斐波那契数列求解

int fibonacciDP1(int n) {       // 动态规划不使用数组
    int a = 0;
    int b = 1;
    int sum;
    int i;

    if (n == 0)return 0;
    if (n == 1)return 1;

    for (int i = 0; i < n - 1; i++) {
        sum = a + b;
        a = b;
        b = sum;
    }
    return sum;
}

int fibonacciDP2(int n) {       // 动态规划使用数组
    int *a = new int[n+1];
    
    a[0] = 0, a[1] = 1;
    for (int i = 2; i < n+1; i++) {
        a[i] = a[i - 1] + a[i - 2];
    }
    return a[n];
}

int fibonacci(int n) {          // 递归法实现斐波那契数列
    if (n == 1 || n == 2) {
        return 1;
    }
    else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}

补充

自下而上的动态规划算法

#include <iostream>
using namespace std;

int temp[100];
int calculate(int *price, int n){
    temp[0] = 0;
    int a;
    for(int i = 1; i <= n; ++i) {
        a = -128;
        for(int j = 1; j <= i; ++j){
            if(a < price[j] + temp[i - j]){
                a = price[j] + temp[i - j];
            }
        }
        temp[i] = a;
    }
    return temp[n];
}

int main() {
    int p[11] = {0,1,5,8,9,10,17,17,20,24,30};
    int n = 10;
    cout<<calculate(p, n)<<endl;

    return 0;
}
    原文作者:野狗子嗷嗷嗷
    原文地址: https://www.jianshu.com/p/94a77571f2d4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞