[LeetCode] 1137. N-th Tribonacci Number 第N个泰波那契数


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


类似题目:

Climbing Stairs

Fibonacci Number


参考资料:

https://leetcode.com/problems/n-th-tribonacci-number/

https://leetcode.com/problems/n-th-tribonacci-number/discuss/345236/JavaC%2B%2BPython-Easy-and-Concise


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2021-06-08 21:59  Grandyang  阅读(691)  评论(0编辑  收藏  举报
Fork me on GitHub