Coding Test Practice/Python

[LeetCode - Easy] 1137. N-th Tribonacci Number

y2r1m 2023. 5. 1. 21:25

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

 

N-th Tribonacci Number - LeetCode

Can you solve this real interview question? 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 E

leetcode.com

 

class Solution:
    def tribonacci(self, n: int) -> int:
        if n == 0: return 0
        elif n in {1, 2}: return 1
        else:
            t = [0, 1, 1] # T_(n+3) 계산을 위한 T_n, T_(n+1), T_(n+2) 저장
            for i in range(3, n):
                tmp = sum(t)
                t[0] = t[1]
                t[1] = t[2]
                t[2] = tmp
            return sum(t)