[LeetCode] N-th Tribonacci Number

코테연습|2025. 5. 21. 22:05

https://leetcode.com/problems/n-th-tribonacci-number/description/?envType=study-plan-v2&envId=leetcode-75

 

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.


피보나치 수열인데, 이제 f(n) = f(n-1) + f(n-2) + f(n-3) 으로 3개씩 더하는 문제다.

/**
 * @param {number} n
 * @return {number}
 */
var tribonacci = function(n) {
    if(n <= 1){
        return n;    
    }
    let n_3 = 0;
    let n_2 = 0;
    let n_1 = 1;
    let n_ = 0;
    for(let i=2; i<=n; i++){
        n_ = n_3 + n_2 + n_1;
        n_3 = n_2;
        n_2 = n_1;
        n_1 = n_; 
    }

    return n_;
};

가장 최근에 풀었던 피보나치 수열 문제가 아직 기억에 남아 있어서 금방 풀 수 있었다~

'코테연습' 카테고리의 다른 글

[LeetCode] House Robber  (0) 2025.05.27
[LeetCode] Fibonacci Number  (0) 2025.05.19
[LeetCode] Count Good Nodes in Binary Tree  (0) 2025.05.15

댓글()