Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e9c8a06

Browse files
斐波那契数列
1 parent 8963130 commit e9c8a06

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎src/com/leetcode_cn/easy/Fib.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.leetcode_cn.easy;
2+
3+
/**
4+
* 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:
5+
*
6+
* F(0) = 0, F(1) = 1
7+
* F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
8+
* 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
9+
*
10+
* 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
11+
*
12+
*
13+
*
14+
* 示例 1:
15+
*
16+
* 输入:n = 2
17+
* 输出:1
18+
* 示例 2:
19+
*
20+
* 输入:n = 5
21+
* 输出:5
22+
*
23+
*
24+
* 提示:
25+
*
26+
* 0 <= n <= 100
27+
*
28+
*/
29+
public class Fib {
30+
public static void main(String[] args) {
31+
int[] arr = new int[101];
32+
int value = fib(5);
33+
System.out.println("fib(n) : " + value);
34+
35+
}
36+
public int fib(int n) {
37+
if (n == 0) return 0;
38+
if (n <= 2) return 1;
39+
arr[1] = 1;
40+
arr[2] = 1;
41+
for (int i = 3; i <= n; i++) {
42+
arr[i] = (arr[i-1] + arr[i-2]) % 1000000007;
43+
}
44+
return arr[n];
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /