1. 斐波那契数列
注意处理输入为0的情况
https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof/
1.1 打表法(tabular)
class Solution {
static const int maxLen = 101;
public:
int fib(int n) {
int a[maxLen] = {0};
a[0] = 0;
a[1] = 1;
for (int i = 2; i <= n; i++) {
a[i] = (a[i-1] + a[i-2]) % 1000000007;
}
return a[n] % 1000000007;
}
};
1.2 记忆化搜索(memorize)
class Solution {
static const int maxLen = 101;
int mem[maxLen] = {0};
public:
int fib(int n) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
if (mem[n] > 0) {
return mem[n];
}
mem[n] = (fib(n-1) + fib(n-2)) % 1000000007;
return mem[n];
}
};
1.3 通项公式 + 矩阵快速幂
class Matrix {
public:
long m[2][2] = {0};
};
class Solution {
public:
int fib(int n) {
if (n == 0) return 0;
if (n == 1 || n == 2) return 1;
Matrix base;
base.m[0][0] = 1;
base.m[0][1] = 1;
base.m[1][0] = 1;
base.m[1][1] = 0;
Matrix res = quickPow(base, n-2);
int num = (res.m[0][0] + res.m[0][1]) % 1000000007;
return num;
}
Matrix matmul(Matrix a, Matrix b) {
Matrix result;
for (int i = 0; i <= 1; i++) {
for (int j = 0; j <= 1; j++) {
for (int k = 0; k <= 1; k++) {
result.m[i][j] = (result.m[i][j] + a.m[i][k] * b.m[k][j]) % 1000000007;
}
}
}
return result;
}
Matrix quickPow(Matrix m, int p) {
if (p == 1) {
return m;
}
if (!(p & 1)) {
Matrix res = quickPow(m, p / 2);
return matmul(res, res);
} else {
Matrix res = quickPow(m, p / 2);
return matmul(matmul(res, res), m);
}
}
};