Leetcode 1137. N-th Tribonacci Number

Problem

The Tribonacci sequence T n T_n Tn is defined as follows:

T 0 = 0 , T 1 = 1 , T 2 = 1 T_0 = 0, T_1 = 1, T_2 = 1 T0=0,T1=1,T2=1, and T n + 3 = T n + T n + 1 + T n + 2 T_{n+3} = T_n + T_{n+1} + T_{n+2} Tn+3=Tn+Tn+1+Tn+2 for n > = 0. n >= 0. n>=0.

Given n n n, return the value of T n T_n Tn.

Algorithm

Calculated using the recursive formula.

Code

class Solution:
    def tribonacci(self, n: int) -> int:
        if n < 2:
            return n
        if n == 2:
            return 1 

        Tn_3, Tn_2, Tn_1, = 0, 1, 1
        for i in range(3, n+1):
            Tn = Tn_1 + Tn_2 + Tn_3
            Tn_3 = Tn_2
            Tn_2 = Tn_1
            Tn_1 = Tn
        
        return Tn

你可能感兴趣的:(Leetcode,解题报告,入门题,leetcode,算法)