当前位置:网站首页>[leetcode refers to offer 10 - I. Fibonacci sequence (simple)]

[leetcode refers to offer 10 - I. Fibonacci sequence (simple)]

2022-04-23 21:20:00 Minaldo7

subject :

Write a function , Input n , Fibonacci, please (Fibonacci) The number of the sequence n term ( namely F(N)). Fibonacci series is defined as follows :

F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), among N > 1.
The Fibonacci series is composed of 0 and 1 Start , The Fibonacci number after that is the sum of the two numbers before .

The answer needs to be modelled 1e9+7(1000000007), If the initial result of calculation is :1000000008, Please return 1.

Example 1:

Input :n = 2
Output :1
Example 2:

Input :n = 5
Output :5

Tips :

0 <= n <= 100

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

With recursion, the timeout will be displayed , So use a loop instead of recursion .

class Solution {
    
    public int fib(int n) {
    
        if(n == 0 || n == 1) return n;
        int front = 0, back = 1, fibn =0;
        for(int i = 2;i<=n;i++){
    
            fibn = front + back;
            if(fibn >= 1000000007)
                fibn -= 1000000007;
            front = back;
            back = fibn;
        }
        return fibn;
    }
}

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479570.html