1137. 第 N 个泰波那契数


官方链接

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

泰波那契序列 Tn 定义如下: 

T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2

给你整数 n,请返回第 n 个泰波那契数 Tn 的值。

 

示例 1:

输入:n = 4
输出:4
解释:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

示例 2:

输入:n = 25
输出:1389537

提示:

  • 0 <= n <= 37
  • 答案保证是一个 32 位整数,即 answer <= 2^31 - 1。

解法一

class Solution {
    public int tribonacci(int n) {

        if (n <= 1) return n;
        if (n == 2) return 1;

        int r0 = 0;
        int r1 = 1;
        int r2 = 1;
        int r3 = 0;
        for (int i = 3; i <= n; i++) {
            r3 = r0 + r1 + r2; 
            r0 = r1;
            r1 = r2;
            r2 = r3;
        }
        return r3;
    }
}

解法二

class Solution {

    Map<Integer, Integer> mem = new HashMap<>();

    public int tribonacci(int n) {

        if (n <= 1) return n;
        if (n == 2) return 1;

        int r0, r1, r2;
        if (mem.containsKey(n-1)) {
            r0 = mem.get(n-1);
        } else {
            r0 = tribonacci(n-1);
            mem.put(n-1, r0);
        }

        if (mem.containsKey(n-2)) {
            r1 = mem.get(n-2);
        } else {
            r1 = tribonacci(n-2);
            mem.put(n-2, r1);
        }

        if (mem.containsKey(n-3)) {
            r2 = mem.get(n-3);
        } else {
            r2 = tribonacci(n-3);
            mem.put(n-3, r2);
        }

        return r0+r1+r2;
    }
}