剑指 Offer 10- I. 斐波那契数列
方法一
class Solution {int mod = (int) 1e9 + 7;public int fib(int n) {if(n <= 1) return n;int[] dp = new int[n + 1];dp[1] = 1;for(int i = 2; i <= n; i++){dp[i] = (dp[i - 1] + dp[i - 2]) % mod;}return dp[n];}
}
方法二
对方法一进行空间优化。
class Solution {int mod = (int) 1e9 + 7;public int fib(int n) {if(n <= 1) return n;int a = 0, b = 1;for(int i = 2; i <= n; i++){int c = (a + b) % mod;a = b;b = c;}return b;}
}