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:
Input: n=5
Output: 7
Approach
Java
public class NThTribonacciNumber {public static void main(String[] args) {int n = 5;System.out.println(tribonacci(n));}static int tribonacci(int n) {int dp[] = new int[n + 1];dp[0] = 0;if (n > 0)dp[1] = 1;if (n > 1)dp[2] = 1;for (int i = 3; i <= n; i++)dp[i] = dp[i - 3] + dp[i - 2] + dp[i - 1];return dp[n];}}
C++
#include <bits/stdc++.h>using namespace std;int tribonacci(int n){int dp[n+1];dp[0]=0;if(n>0)dp[1]=1;if(n>1)dp[2]=1;for(int i=3;i<=n;i++)dp[i]=dp[i-3]+dp[i-2]+dp[i-1];return dp[n];}int main(){int n=5;cout<<tribonacci(n);return 0;}
No comments:
Post a Comment