剑指 Offer 10- I. 斐波那契数列

https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/

  • 自己的解答
class Solution {
    public int fib(int n) {
        int[] arr = new int[101];
        arr[0]=0;
        arr[1]=1;
        for(int i=2;i<101;i++){
            arr[i] = arr[i-1] + arr[i-2];
            arr[i] %= 1000000007;
        }
        return arr[n];
    }
}
  • 减少空间改进方法
class Solution {
    public int fib(int n) {
        int a = 0, b = 1, sum;
        for(int i = 0; i < n; i++){
            sum = (a + b) % 1000000007;
            a = b;
            b = sum;
        }
        return a;
    }
}

你可能感兴趣的:(剑指 Offer 10- I. 斐波那契数列)