The Tribonacci sequence Tn
is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
Given n
, return the value of Tn
.
Example 1:
Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:
Input: n = 25
Output: 1389537
Constraints:
0 <= n <= 37
- The answer is guaranteed to fit within a 32-bit integer, ie.
answer <= 2^31 - 1
.
Thought:
- 数组中套循环
class Solution {
public:
int tribonacci(int n) {
int* dp = new int[n + 1];
dp[0] = 0;
if(n >= 1) dp[1] = 1;
if(n >= 2) dp[2] = 1;
for(int i = 3; i <= n; i++)
{
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
}
int res = dp[n];
delete[] dp;
return res;
}
};
- 观察官方题解,发现方法一可以对我的代码的空间复杂度做出优化!
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;
}
};
显然,题解给出的滑动窗口更好!
方法二,事实上能用数学知识优化的代码效率更高效,
只可惜,鄙人学完了线性代数还是没有想到!
/*
* @lc app=leetcode.cn id=1137 lang=cpp
*
* [1137] 第 N 个泰波那契数
*/
// @lc code=start
class Solution {
public:
int tribonacci(int n) {
if (n == 0) {
// 如果n为0,返回0
return 0;
}
if (n <= 2) {
// 如果n小于等于2,返回1
return 1;
}
vector<vector<long>> q = {
{
1, 1, 1}, {
1, 0, 0}, {
0, 1, 0}}; // 初始化矩阵q
vector<vector<long>> res = pow(q, n); // 计算矩阵q的n次方
return res[0][2]; // 返回矩阵q的(1,3)位置的值
}
vector<vector<long>> pow(vector<vector<long>>& a, long n) {
// 计算矩阵a的n次方
vector<vector<long>> ret = {
{
1, 0, 0}, {
0, 1, 0}, {
0, 0, 1}}; // 初始化单位矩阵
while (n > 0) {
// 当n大于0时
if ((n & 1) == 1) {
// 如果n为奇数
ret = multiply(ret, a); // 计算ret和a的乘积
}
n >>= 1; // n右移一位
a = multiply(a, a); // 计算a的平方
}
return ret; // 返回ret
}
vector<vector<long>> multiply(vector<vector<long>>& a, vector<vector<long>>& b) {
// 计算矩阵a和矩阵b的乘积
vector<vector<long>> c(3, vector<long>(3)); // 初始化结果矩阵c
for (int i = 0; i < 3; i++) {
// 遍历矩阵a的行
for (int j = 0; j < 3; j++) {
// 遍历矩阵b的列
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]; // 计算c[i][j]的值
}
}
return c; // 返回结果矩阵c
}
};
// @lc code=end