418，剑指 Offer-斐波那契数列

F(0) = 0, F(1) = 1

F(N) = F(N - 1) + F(N - 2),

• 0 <= n <= 100

public int fib(int n) {
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}


int constant = 1000000007;

public int fib(int n) {
if (n < 2)
return n;
int first = fib(n - 1) % constant;
int second = fib(n - 2) % constant;
return (first + second) % constant;
}


int constant = 1000000007;

public int fib(int n) {
return fib(n, new HashMap());
}

public int fib(int n, Map<Integer, Integer> map) {
if (n < 2)
return n;
if (map.containsKey(n))
return map.get(n);
int first = fib(n - 1, map) % constant;
map.put(n - 1, first);
int second = fib(n - 2, map) % constant;
map.put(n - 2, second);
int res = (first + second) % constant;
map.put(n, res);
return res;
}


public int fib(int n) {
int constant = 1000000007;
int first = 0;
int second = 1;
while (n-- > 0) {
int temp = first + second;
first = second % constant;
second = temp % constant;
}
return first;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

数据结构和算法

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-14

05-30 521
04-15 100
07-20 257
03-17 60
02-17 76
01-09 69