【剑指Offer10】斐波那契数列

动态规划

/**
 * 剑指 Offer 10- I. 斐波那契数列
 * https://leetcode.cn/problems/fei-bo-na-qi-shu-lie-lcof/
 * 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
 *
 * 思路:动态规划
 * */
public class Solution1 {
    private static final int MOD = (int)Math.pow(10, 9) + 7; // 1e9 + 7

    public int fib(int n) {
        if (n <= 1) {
            return n;
        }
        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]) % MOD;
        }
        return dp[n];
    }
}

动态规划 + 滚动数组

public class Solution2 {
    private static final int MOD = (int)Math.pow(10, 9) + 7; // 1e9 + 7

    public int fib(int n) {
        if (n <= 1) {
            return n;
        }
        int a = 0;
        int b = 1;
        for (int i = 2; i <= n; i++) {
            int c = (b + a) % MOD;
            a = b;
            b = c;
        }
        return a;
    }
}

青蛙跳台阶问题

/**
 * 剑指 Offer 10- II. 青蛙跳台阶问题
 * https://leetcode.cn/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/
 * */
public class Solution3 {
    public int numWays(int n) {
        if (n == 0) {
            return 1;
        }
        int a = 1;
        int b = 2;
        for (int i = 2; i <= n; i++) {
            int c = (b + a) % 1000000007; // f(n) = f(n-1) + f(n-2)
            a = b;
            b = c;
        }
        return a;
    }
}
posted @ 2022-06-24 23:05  廖子博  阅读(22)  评论(0编辑  收藏  举报