第 N 个泰波那契数

泰波那契序列 Tn 定义如下:
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2给你整数 n,请返回第 n 个泰波那契数 Tn 的值。

来源:力扣(LeetCode)

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

读完题之后,第一反应是递归,不少做完的大佬说超时了。

看到好多大佬写的算法,从别的角度看待,又学会了好多新的解题思路。

在此收藏一下。用于自我学习:

public class Q1137_test1 {
    public int tribonacci(int n) {
        int a = 0, b = 1, c = 1;
        while (n-- > 0) {
            int t = b;
            c = a + b + c;
            b = c - a - b;
            a = c - t - b;
        }
        return a;
    }
}

作者:liu-xing-0923
链接:https://leetcode-cn.com/problems/n-th-tribonacci-number/solution/dong-tai-gui-hua-ji-jian-dai-ma-by-liu-xing-3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
code blockpublic int tribonacci(int n) {
        switch (n) {
            case 0:
                return 0;
            case 1:
                return 1;
            case 2:
                return 1;
            case 3:
                return 2;
            case 4:
                return 4;
            default:
                return  2 * tribonacci(n - 1) - tribonacci(n - 4);
        }
    }

你可能感兴趣的:(算法)