lc.509 斐波那契
- DP 滚动数组
class Solution {
public:
int fib(int n) {
int f[31];
f[0]=0;
f[1]=1;
for(int i=2;i<=n;i++)
{
f[i]=f[i-1]+f[i-2];
}
return f[n];
}
};
- 矩阵快速幂 快速幂算法O(logn)
class Solution {
public:
int fib(int n) {
if (n < 2) {
return n;
}
vector<vector<int>> q{{1, 1}, {1, 0}};
vector<vector<int>> res = matrix_pow(q, n - 1);
return res[0][0];
} //返回res[0][0]==Fn
//由于f0=0,f1=1,res*[1;0]等于res,所以没必要再乘[1;0]
vector<vector<int>> matrix_pow(vector<vector<int>>& a, int n) {
vector<vector<int>> ret{{1, 0}, {0, 1}};
while (n > 0) {
if (n & 1) {
ret = matrix_multiply(ret, a); //矩阵与矩阵[1,0;0,1]相乘等于其本身
}
n >>= 1;
a = matrix_multiply(a, a);
}
return ret;
} //快速幂实现a^n 函数matrix_pow
vector<vector<int>> matrix_multiply(vector<vector<int>>& a, vector<vector<int>>& b) {
vector<vector<int>> c{{0, 0}, {0, 0}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];
}
}
return c;
} //实现两个矩阵a,b相乘 函数matrix_multiply
};
我只觉得妙不堪言
- 数学方法,通项公式
class Solution {
public:
int fib(int n) {
double sqrt5 = sqrt(5);
double fibN = pow((1 + sqrt5) / 2, n) - pow((1 - sqrt5) / 2, n);
return round(fibN / sqrt5);
}
};
lc.1137 泰波那契
Tn=Tn-1+Tn-2+Tn-3
其中,T1=0,T2=1,T3=1
- DP
class Solution {
public:
int tribonacci(int n) {
if (n == 0)
{
return 0;
}
if (n <= 2)
{
return 1;
}
int p = 0, q = 0, r = 1, s = 1;
for (int i = 3; i <= n; ++i)
{
p = q;
q = r;
r = s;
s = p + q + r;
}
return s;
}
};
- 快速幂
class Solution {
public:
int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n <= 2) {
return 1;
}
vector<vector<long>> q = {{1, 1, 1}, {1, 0, 0}, {0, 1, 0}};
vector<vector<long>> res = pow(q, n);
return res[0][2];
}
vector<vector<long>> pow(vector<vector<long>>& a, long n) {
vector<vector<long>> ret = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
while (n > 0) {
if ((n & 1) == 1) {
ret = multiply(ret, a);
}
n >>= 1;
a = multiply(a, a);
}
return ret;
}
vector<vector<long>> multiply(vector<vector<long>>& a, vector<vector<long>>& b) {
vector<vector<long>> c(3, vector<long>(3));
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
}
}
return c;
}
};
和 lc.509 差不多,依然是构造了multiply和pow两个函数来使用快速幂,二维变三维。
注意到可以用函数的构造,也同样可以使用字符重载。