1137. N-th Tribonacci Number
Difficulty: 简单
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
.
Solution 1
首先就是递归写法,结果意料中的运行超时
Language: c++
class Solution {
public:
int tribonacci(int n) {
if(n == 0 || n == 1)
return n;
else if (n == 2)
return 1;
else{
return tribonacci(n - 1) + tribonacci(n -2) + tribonacci(n-3);
}
}
};
由于限制个数最多到37,因此不出意料的超时。因此,记录下重复计算的项节约时间。
Solution 2
Language: c++
class Solution
{
public:
int tribonacci(int n)
{
if (n == 0 || n == 1)
return n;
else if (n == 2)
return 1;
else
{
int a[50];
a[0] = 0, a[1] = 1, a[2] = 1;
//Tn+3 = Tn + Tn+1 + Tn+2
for (int i = 3; i <= n; ++i)
{
a[i] = a[i - 1] + a[i - 2] + a[i - 3];
}
return a[n];
}
}
};
考虑到开辟了一次长度为50的数组,空间复杂度似乎可以进一步降低,因为每个值只与前三个数相关。因此整三个变量就行了。
Solution 3
Language: c++
class Solution
{
public:
int tribonacci(int n)
{
if (n == 0 || n == 1)
return n;
else if (n == 2)
return 1;
else
{
int a = 0, b = 1, c = 1;
//Tn+3 = Tn + Tn+1 + Tn+2
for (int i = 3; i <= n; ++i)
{
c = a + b + c;
b = c - a - b;
a = c - a - b;
}
return c;
}
}
};