Coding
1137. N-th Tribonacci Number
On this page
⭐
題目敘述
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 T4= 1 + 1 + 2 = 4
Example 2
Input: n = 25 Output: 1389537
解題思路
Solution
class Solution {
public int tribonacci(int n) {
int[] Tn = new int[] {0, 1, 1, 0};
switch(n){
case 0:
return Tn[0];
case 1:
return Tn[1];
case 2:
return Tn[2];
}
for(int i = 3; i <= n; i++){
Tn[3] = Tn[2] + Tn[1] + Tn[0];
Tn[0] = Tn[1];
Tn[1] = Tn[2];
Tn[2] = Tn[3];
}
return Tn[3];
}
}