Skip to content

[剑指 Offer] 10- I. 斐波那契数列 #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Jul 23, 2021 · 0 comments
Open

[剑指 Offer] 10- I. 斐波那契数列 #34

frdmu opened this issue Jul 23, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Jul 23, 2021

写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。斐波那契数列的定义如下:

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.

斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

 

示例 1:

输入:n = 2
输出:1

示例 2:

输入:n = 5
输出:5

提示:

  • 0 <= n <= 100




递归会超时,记忆化搜索吧。代码如下:

class Solution {
public:
    int mod = 1e9 + 7; 
    int fib(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        
        int pre = 0;
        int cur = 1;
        int now;
        for (int i = 2; i <= n; i++) {
            now = (pre + cur)%mod;
            pre = cur;
            cur = now;     
        } 
        
        return now;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant