目录结构
1.题目
斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:
- F(0) = 0, F(1) = 1
- F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
给定 N,计算 F(N)。
示例:
入:2
输出:1
解释:F(2) = F(1) + F(0) = 1 + 0 = 1.
输入:3
输出:2
解释:F(3) = F(2) + F(1) = 1 + 1 = 2.
输入:4
输出:3
解释:F(4) = F(3) + F(2) = 2 + 1 = 3.
提示:
- 0 ≤
N
≤ 30
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fibonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
2.1递归
public class Solution509 {
@Test
public void test509() {
for (int i = 0; i < 20; i++) {
System.out.println(fib(i));
}
}
public int fib(int N) {
if (N == 0) {
return 0;
}
if (N == 1) {
return 1;
}
return fib(N - 1) + fib(N - 2);
}
}
- 时间复杂度:
- 空间复杂度:
2.2迭代
public class Solution509 {
@Test
public void test509() {
for (int i = 0; i < 20; i++) {
System.out.println(fib(i));
}
}
public int fib(int N) {
if (N == 0) {
return 0;
}
if (N == 1) {
return 1;
}
int pre2 = 0, pre1 = 1, current = 0;
for (int i = 2; i <= N; i++) {
current = pre1 + pre2;
pre2 = pre1;
pre1 = current;
}
return current;
}
}
- 时间复杂度:
- 空间复杂度:
2.3公式法
public class Solution509 {
@Test
public void test509() {
for (int i = 0; i < 20; i++) {
System.out.println(fib(i));
}
}
public int fib(int N) {
double p1 = (1 + Math.sqrt(5)) / 2;
double p2 = (1 - Math.sqrt(5)) / 2;
return (int) Math.round((Math.pow(p1, N) - Math.pow(p2, N)) / Math.sqrt(5));
}
}
- 时间复杂度:
- 空间复杂度: