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
.
這道題讓求一個三元的斐波那契數列,我們對斐波那契數列應該都不陌生,當前的數字為前兩個數字之和。舉個生動的例子,大學食堂里今天的湯是昨天的湯加上前天的湯,只不過這里還要加上大前天的湯,哈哈~ 本質上跟之前那道 Fibonacci Number 沒有啥太大的區別,這里 OJ 已經抹殺了不用記憶數組的暴力遞歸的方法了,這里博主就直接上最優解了,並不需要整個數組來記錄所有數字,其實跟當前數字相關的只有前面的三個數字,所以使用三個變量就行了。前三個數字確定了,直接初始化好,然后i從2遍歷到n,先把 first 保存到另一個變量t中,然后 first 更新為 second,second 更新為 third,third 更新為新的 first,second 和 t 之和,最終返回 third 即可,參見代碼如下:
class Solution {
public:
int tribonacci(int n) {
if (n < 2) return n;
int first = 0, second = 1, third = 1;
for (int i = 2; i < n; ++i) {
int t = first;
first = second;
second = third;
third = t + first + second;
}
return third;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1137
類似題目:
參考資料:
https://leetcode.com/problems/n-th-tribonacci-number/