LeetCode 1137. N-th Tribonacci Number
考点 | 难度 |
---|---|
Dynamic Programming | Easy |
题目
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(un-calculated)。如果n
位置上不是-1,返回那个值,否则通过斐波那契数列的计算公式用前三位数字算出n
位置的数。
答案
class Solution {
int[] memo;
Solution() {
// Initialize memo, with -1 as flags for not calculated
memo = new int[38]; // 0 through 37
memo[0] = 0;
memo[1] = 1;
memo[2] = 1;
for(int i = 3; i < memo.length; i++) memo[i] = -1;
}
public int tribonacci(int n) {
// If we have already calculated value, return it.
if(memo[n] != -1) {
return memo[n];
}
else {
int result = tribonacci(n-3) + tribonacci(n-2) + tribonacci(n-1);
memo[n] = result;
return result;
}
}
}