N-th Tribonacci Number
Posted setnull
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
我写的code:
Map<Integer, Integer> map = new HashMap<>();
public int tribonacci(int n)
if (n == 0)
return 0;
if (n == 1 || n == 2) return 1;
if (map.containsKey(n)) return map.get(n);
int sum = tribonacci(n - 1) + tribonacci(n - 2) + tribonacci(n - 3);
map.put(n, sum);
return sum;
别人的code:
public int tribonacci(int n)
if (n < 2) return n;
int a = 0, b = 1, c = 1, d;
while (n-- > 2)
d = a + b + c;
a = b;
b = c;
c = d;
return c;
public static int tribonacci(int n)
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
dp[2] = 1;
for (int i = 3; i <= n; i++)
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
return dp[n];
// Recursion is slow. Memorization is better, but bottom up approach is the best here.
public int tribonacci(int n)
int[] t = new int[] 0,1,1;
for (int i = 3; i <= n; i++)
int sum = t[0] + t[1] + t[2];
t[0] = t[1];
t[1] = t[2];
t[2] = sum;
return t[2];
以上是关于N-th Tribonacci Number的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode --- 1137. N-th Tribonacci Number 解题报告
LeetCode --- 1137. N-th Tribonacci Number 解题报告
UVA12470—Tribonacci (类似斐波那契,简单题)