The Tribonacci sequence Tn is defined as follows: 
T0 = 0, T1 = 1, T2 = 1, and T_{n+3} = T_n + T_{n+1} + T_{n+2} for n >= 0.
Given n, return the value of Tn.

Example 1:
Input: n = 4
Output: 4
Explanation:
T3 = 0 + 1 + 1 = 2
T4 = 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.

Solution in python:

class Solution:
    def tribonacci(self, n: int) -> int:
        t0, t1, t2 = 0, 1, 1
        if n <= 1:
            return n
        elif n == 2:
            return 1
        t3 = None
        while n - 2 > 0:
            t3 = t0 + t1 + t2
            t0, t1, t2 = t1, t2, t3
            n -= 1
        return t3
最后修改日期: 2021年3月5日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。