动态规划入门:以斐波那契分析动态规划

递归

最原始的解法,教科书上都是这样写的

class Solution {
    public int fib(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fib(n-1)+fib(n-2);
    }
}

记忆化递归

用一个数组保存递归的结果
是一自顶向下的解法,是传统递归的改进

class Solution {
    public static int mod = 1000000007;
    public static int[] array = new int[101];//设置一个最大数组,初始值全部为0
    public int fib(int n) {
        if (n == 0) return 0;
        Solution.array[1] = 1;
        if (n == 1) return 1;
        if (Solution.array[n] != 0) return Solution.array[n];
        Solution.array[n] = (fib(n-1)+fib(n-2))%1000000007;
        return Solution.array[n];
    }
}

动态规划

自底向上
空间复杂度为O(n),因为用了一个数组来存数据

class Solution {
    public int fib(int n) {
        if(n == 0) return 0;
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        for(int i = 2; i <= n; i++){
            dp[i] = dp[i-1] + dp[i-2];
            dp[i] %= 1000000007;
        }
        return dp[n];
    }
}

动态规划(移动数组)

自底向上
是动态规划的优化解法,空间复杂度更低,只使用了2个变量的空间

class Solution {
    public int fib(int n) {
        int mod = 1000000007;
        if(n == 0) return 0;
        if(n == 1) return 1;


        int first =0;
        int second=0;
        int last = 1;

        for(int i = 2;i <= n;i ++){
            first=second;
            second=last;
            last=(first+second)%mod;//每一个数字都要取模,不是在最终结果取模
        }

        return last;
    }
}
posted @ 2022-10-12 15:36  猪猪猪猪侠  阅读(26)  评论(0编辑  收藏  举报