LeetCode 1137. N-th Tribonacci Number Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1137. N-th Tribonacci Number

Description

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.

Solutions

Solution 1: Dynamic Programming

According to the recurrence relation given in the problem, we can use dynamic programming to solve it.

We define three variables a, b, c to represent Tn-3, Tn-2, Tn-1, respectively, with initial values of 0, 1, 1.

Then we decrease n to 0, updating the values of a, b, c each time, until n is 0, at which point the answer is a.

The time complexity is O(n), and the space complexity is O(1). Here, n is the given integer.

PythonJavaC++GoTypeScriptJavaScriptPHP
class Solution: def tribonacci(self, n: int) -> int: a, b, c = 0, 1, 1 for _ in range(n): a, b, c = b, c, a + b + c return a(code-box)

Solution 2: Matrix Exponentiation to Accelerate Recurrence

We define Tib(n) as a 1 × 3 matrix \begin{bmatrix} Tn & Tn - 1 & Tn - 2 \end{bmatrix}, where Tn, Tn - 1 and Tn - 2 represent the nth, (n - 1)th and (n - 2)th Tribonacci numbers, respectively.

We hope to derive Tib(n) from Tib(n-1) = \begin{bmatrix} Tn - 1 & Tn - 2 & Tn - 3 \end{bmatrix}. That is, we need a matrix base such that Tib(n - 1) × base = Tib(n), i.e.,

\begin{bmatrix} Tn - 1 & Tn - 2 & Tn - 3 \end{bmatrix} × base = \begin{bmatrix} Tn & Tn - 1 & Tn - 2 \end{bmatrix}

Since Tn = Tn - 1 + Tn - 2 + Tn - 3, the matrix base is:

\begin{bmatrix} 1 & 1 & 0 \ 1 & 0 & 1 \ 1 & 0 & 0 \end{bmatrix}

We define the initial matrix res = \begin{bmatrix} 1 & 1 & 0 \end{bmatrix}, then Tn is equal to the sum of all elements in the result matrix of res multiplied by basen - 3. This can be solved using matrix exponentiation.

The time complexity is O(log n), and the space complexity is O(1).

PythonJavaC++GoTypeScriptJavaScriptPHP
import numpy as np class Solution: def tribonacci(self, n: int) -> int: if n == 0: return 0 if n < 3: return 1 factor = np.asmatrix([(1, 1, 0), (1, 0, 1), (1, 0, 0)], np.dtype("O")) res = np.asmatrix([(1, 1, 0)], np.dtype("O")) n -= 3 while n: if n & 1: res *= factor factor *= factor n >>= 1 return res.sum()(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !