Algorithm


Problem Name: 1137. N-th Tribonacci Number

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

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.

 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int tribonacci(int n) {
    if (n <= 2) {
      return n == 0 ? 0 : 1;
    }
    int[] dp = new int[n + 1];
    dp[1] = dp[2] = 1;
    for (int i = 3; i  < = n; i++) {
      dp[i] = dp[i - 2] + dp[i - 1] + dp[i - 3];
    }
    return dp[n];
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 4

Output

x
+
cmd
4

#2 Code Example with Javascript Programming

Code - Javascript Programming


const hash = {}
const tribonacci = function(n) {
  if(n === 0) return 0
  if(n === 2 || n === 1) return 1
  if(hash[n] != null) return hash[n]
  let tmp = tribonacci(n - 3) + tribonacci(n - 2) + tribonacci(n - 1)
  return hash[n] = tmp
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 4

Output

x
+
cmd
4

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def tribonacci(self, n: int) -> int:
        t0, t1, t2 = 0, 1, 1
        for _ in range(n):
            t0, t1, t2 = t1, t2, t0 + t1 + t2
        return t0
        
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 25

Output

x
+
cmd
1389537

#4 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    public class _1137_NThTribonacciNumber
    {
        private int[] memo = new int[38];

        public _1137_NThTribonacciNumber()
        {
            memo[0] = 0;
            memo[1] = 1;
            memo[2] = 1;
        }

        public int Tribonacci(int n)
        {
            if (n  <  3) return memo[n];
            if (memo[n] != 0) return memo[n];

            for (int i = 3; i  < = n; i++)
            {
                if (memo[i] != 0) continue;
                memo[i] = memo[i - 1] + memo[i - 2] + memo[i - 3];
            }

            return memo[n];
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 25

Output

x
+
cmd
1389537
Advertisements

Demonstration


Previous
#1131 Leetcode Maximum of Absolute Value Expression Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1138 Leetcode Alphabet Board Path Solution in C, C++, Java, JavaScript, Python, C# Leetcode