斐波那契数【动态规划】

  1. 斐波那契数
    斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:

F(0) = 0,F(1) = 1
F(n) = F(n - 1) + F(n - 2),其中 n > 1
给定 n ,请计算 F(n) 。
在这里插入图片描述

class Solution {
    
    
    public int fib(int n) {
    
    
        if (n <= 1) return n;
        int[] dp = new int[n + 1];//1.定义dp,表示F(i), 从0开始,到n有 n+1 个数
        dp[0] = 0;//3.dp数组的初始化,初始化前两个数
        dp[1] = 1;
        for (int index = 2; index <= n; index++) {
    
    //4.遍历顺序:正序
            dp[index] = dp[index - 1] + dp[index - 2];//2.递推公式
        }//5.举例推导dp数组,验证正确性
        return dp[n];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_47004707/article/details/132640623