Friday, September 24, 2021

[LeetCode] N-th Tribonacci Number

Problem: 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:

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


Approach: The problem is just like finding nth fibonacci number. Here we just need to add 3 previous numbers. That's all!


Implementation in C#:

    public int Tribonacci(int n)
    {        
        if (n <= 1)
        {
            return n;
        }
        if (n == 2)
        {
            return 1;
        }
        int t0 = 0, t1 = 1, t2 = 1;
        for (int i = 3; i <= n; ++i)
        {
            int t = t0 + t1 + t2;
            t0 = t1;
            t1 = t2;
            t2 = t;
        }
        return t2;
    }


Complexity: O(n)

No comments:

Post a Comment