代码改变世界

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

2021-05-08 23:58  jetwill  阅读(46)  评论(0编辑  收藏  举报

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

Python 2

class Solution(object):
    def fib(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 2 :
            return n
        
        prev = 0
        curr = 1
        next = 0
        for i in range(2, n+1):
            next = (prev + curr) % 1000000007
            prev = curr
            curr = next
        
        return next

Java

class Solution {
    public int fib(int n) {
        if( n < 2 ){
            return n;
        }
        int prev = 0;
        int curr = 1;
        int next = 0;
        for(int i = 2; i <= n; i++){
            next = (prev + curr) % 1000000007;
            prev = curr;
            curr = next;
        }
        return next;
    }
}

Python 3

class Solution:
    @lru_cache(None)
    def fib(self, n: int) -> int:
        if n < 2:
            return n
        return (self.fib(n-1) + self.fib(n-2)) % 1000000007