I got below recursive function written in Java. I wanted to convert it to a Dynamic program but I don't know it is right or not? I think I'm missing something here. Any guidance would be perfect.
//Prints newRec(4,4) for example.
public static int newRec(int k, int t){
if (k<3)
return 1;
if (t<3)
return 2;
return newRec(k-1,t-1)+newRec(k-1,t-2)+newRec(k-2,t-3);
}
Dynamic program
public static int newDP(int k, int t) {
//Initialize 2D Array to save bottom-up values
int[][] saved = new int[k + 1][t + 1];
for (int i = 0; i<=k; i++)
{
for(int j=0; j<=t; j++)
{
//Eliminate constants. saved[0][j]=saved[1][j]=saved[2][j]=1
if(i < 3 ) {
saved[i][j] = 1;
}
//Eliminate constants. saved[i][0]=saved[i][1]=saved[i][2]=2
else if(j < 3 ) {
saved[i][j] = 2;
}
//Calculate rest of the values until you reach the wanted newDP(k, t)
else {
saved[i][j] = saved[i - 1][j - 1] + saved[i - 1][j - 2] + saved[i - 2][j - 3];
}
}
}
//Return wanted value
return saved[k][t];
}
Best.