Published
- 1 min read
NTribonacci number problem bottom up approach dynamic programming
NTribonacci number Dynamic Programming Problem
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.
- Why this is a dp problem - because we are asked to generate fibonacci number whcih depends on the last number fibonacci, so its a repeated sub problem
- During recursion we would be able to calculate previous number fibonacci.
- The code snippet shows reverse recurssion, starting from n-1 things are calculated till we reach the starting
- The code below shows bottom up memoization with recursion
System.out.println(tribonacciNumber.nTribonacciNumber(n, dp))
private int nTribonacciNumberBottomUp(int n, int dp[]){
/**This is a top down apprach with memoziation */
if(n < 3) {
return n == 0 ? 0 : 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];
}