首页 > 其他分享 >代码随想录——动态规划

代码随想录——动态规划

时间:2023-01-28 14:12:33浏览次数:54  
标签:return int 代码 随想录 Solution fib 动态 public

斐波那契数

题目 简单

class Solution {
    public int fib(int n) {
        if (n < 2) return n;
        int a = 0, b = 1, c = 0;
        for (int i = 1; i < n; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
}
//非压缩状态的版本
class Solution {
    public int fib(int n) {
        if (n <= 1) return n;             
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        for (int index = 2; index <= n; index++){
            dp[index] = dp[index - 1] + dp[index - 2];
        }
        return dp[n];
    }
}

 

标签:return,int,代码,随想录,Solution,fib,动态,public
From: https://www.cnblogs.com/CWZhou/p/17070206.html

相关文章