[LeetCode] N-th Tribonacci Number

1137. 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.

1
2
3
4
5
6
7
8
9
class Solution {
int dp[38] = {0,};
public:
int tribonacci(int n) {
if(n <= 2) return n ? 1 : 0;
if(dp[n]) return dp[n];
return dp[n] = tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/01/PS/LeetCode/n-th-tribonacci-number/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.