链接:https://leetcode-cn.com/problems/fibonacci-number/
斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
给定 N,计算 F(N)。
示例 1:
输入:2
输出:1
解释:F(2) = F(1) + F(0) = 1 + 0 = 1.
示例 2:
输入:3
输出:2
解释:F(3) = F(2) + F(1) = 1 + 1 = 2.
示例 3:
输入:4
输出:3
解释:F(4) = F(3) + F(2) = 2 + 1 = 3.
提示:
0 ≤ N ≤ 30
1.递归
2.用数组保存
3.
class Solution {
public:
int fib(int N) {
int a = 0;
int b = 1;
int c = 0;
if(N == 0) return 0;
if(N == 1) return 1;
else
{
N -= 1;
while(N--)
{
c = a + b;
a = b;
b = c;
}
}
return c;
}
};
4.记忆化
class Solution {
public:
int fib(int N) {
if (N <= 1) {
return N;
}
return memoize(N);
}
int memoize(int N) {
int cache[N + 1];
cache[1] = 1;
for (int i = 2; i <= N; i++) {
cache[i] = cache[i-1] + cache[i-2];
}
return cache[N];
}
}
5.矩阵乘法
// leetcode官方题解代码
class Solution {
int fib(int N) {
if (N <= 1) {
return N;
}
int[][] A = new int[][]{{1, 1}, {1, 0}};
matrixPower(A, N-1);
return A[0][0];
}
void matrixPower(int[][] A, int N) {
if (N <= 1) {
return;
}
matrixPower(A, N/2);
multiply(A, A);
int[][] B = new int[][]{{1, 1}, {1, 0}};
if (N%2 != 0) {
multiply(A, B);
}
}
void multiply(int[][] A, int[][] B) {
int x = A[0][0] * B[0][0] + A[0][1] * B[1][0];
int y = A[0][0] * B[0][1] + A[0][1] * B[1][1];
int z = A[1][0] * B[0][0] + A[1][1] * B[1][0];
int w = A[1][0] * B[0][1] + A[1][1] * B[1][1];
A[0][0] = x;
A[0][1] = y;
A[1][0] = z;
A[1][1] = w;
}
}
6.公式