Description
e 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
.
Analyse
类似于fibonacci,由两项的递推变成了三项,也就是tribonacci
T0 = 0
T1 = 1
T2 = 1
Tn+3 = Tn + Tn+1 + Tn+2
构造一个递推公式,直接用递归来做,写起来很简单,可是超时了,原因是很多数据重复计算了
int tribonacci(int n) {
if (n == 0 || n == 1) return n;
if (n == 2) return 1;
return tribonacci(n-3) + tribonacci(n-2) + tribonacci(n-1);
}
改用动态规划的思想,AC了
int tribonacci(int n) {
int list[38] = {0, 1, 1,};
if (n < 3) return list[n];
for (int i = 3; i <= n; i++)
{
list[i] = list[i-3] + list[i-2] + list[i-1];
}
return list[n];
}
但还是比LeetCode上其他代码要慢,看了下更快的代码,唯一的差别就是把数组换成了vector
int tribonacci(int n) {
vector<int> list(38);
int *list = (int*)malloc(sizeof(int) * 38); // 速度和数组一样,也比vector慢
list[0] = 0;
list[1] = 1;
list[2] = 1;
for (int i = 3; i <= n; i++)
{
list[i] = list[i-3] + list[i-2] + list[i-1];
}
return list[n];
}