LeetCode //C - 1137. N-th Tribonacci Number
1137. N-th Tribonacci Number
The Tribonacci sequenceT n T_nTnis defined as follows:
T 0 = 0 , T 1 = 1 , T 2 = 1 , a n d T n + 3 = T n + T n + 1 + T n + 2 f o r n > = 0. T_0 = 0, T_1 = 1, T_2 = 1, and T_{n+3} = T_n + T_{n+1} + T_{n+2} for n >= 0.T0=0,T1=1,T2=1,andTn+3=Tn+Tn+1+Tn+2forn>=0.
Given n, return the value ofT n T_nTn.
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.
From: LeetCode
Link: 1137. N-th Tribonacci Number
Solution:
Ideas:
Iteratively calculate Tribonacci numbers
using the previous 3 values only.
Code:
inttribonacci(intn){if(n==0)return0;if(n==1||n==2)return1;inta=0,b=1,c=1;for(inti=3;i<=n;i++){intd=a+b+c;a=b;b=c;c=d;}returnc;}