Published
- 1 min read
NTribonacci number problem top down 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 top down memoization with recursion
System.out.println(tribonacciNumber.nTribonacciNumber(n, dp))
private int nTribonacciNumber(int n, int dp[]){
/**This is a top down apprach with memoziation */
if(n < 0) {
return 0;
}
if( n == 0) {
return 0;
}
if(n == 1 || n ==2 ){
return 1;
}
if(dp[n] >=0) { //way of using the saved values
System.out.println("Reusing results : "+ dp[n]);
return dp[n];
}
dp[n] = nTribonacciNumber(n-2, dp) + nTribonacciNumber(n-1, dp) + nTribonacciNumber(n-3, dp);
return dp[n];
}