I'm trying to implement a function to calculate trinomial coefficient in Java using dynamic programming. I'm using the formula:
T(n,k)= 1 if n=0 and k=0
T(n,k)= 0 if k<-n or k>n
T(n,k)=T(n-1,k-1)+T(n-1,k)+T(n-1,k+1)
I'm using a 2D array to store results of all sub-problems. However, the result I get for a particular n
and k
is very far from the correct answer. Here is my implementation of the method:
public static long trinomial(int n, int k) {
if (n == 0 && k == 0) return 1;
if (k < -n || k > n) return 0;
long[][] T = new long[n+1][2*n+3];
T[0][(2*n+3)/2] = 1;
for (int i = 1; i <= n; i++) {
for (int j = -i; j <= i; j++) {
T[i][j+n+1] = T[i-1][j+n] + T[i-1][j+n+1] + T[i-1][j+n+2];
}
}
if (k < 0) return T[n][k+n];
else return T[n][k];
}
I get T(24,12) = 123286440
. However, the correct answer is: 287134346
.
I get T(3,3) = 6
. But the correct answer is 1
.
When I computed T(3,3)
on a paper using the same method, I get T(3,3) = 1
but in computer I get the wrong answer. There are no compilation errors.