A bit late but for the ones who are looking for a complete solution here is mine below. First I suggest to others to read the answer given here: https://stackoverflow.com/a/6165124/4636721 to understand what dynamic programming, memoization and tabulation mean
Anyway about my solution so basically we have the given method:
// Not efficient at all
private static double binomial(int N, int k, double p)
{
if (N == 0 && k == 0)
{
return 1.0;
}
else if ((N < 0) || (k < 0))
{
return 0.0;
}
else
{
return (1.0 - p) * binomial(N - 1, k, p) + p * binomial(N - 1, k - 1, p);
}
}
Yes this is really slow... the number of recursive calls is kinda big (about ~N^2)
Yes you can use the memoization approach which is basically as others have already stated basically caching values that have been previously computed.
For some people memoization imply to keep the recursive strategy and checking the value we need has been calculated or not, if not the program has to compute it and cache it, it's really easy to implement:
private static double binomialTopDown(int N, int k, double p)
{
double[][] cache = new double[N + 1][k + 1];
for (int i = 0; i < (N + 1); i++)
{
Arrays.fill(cache[i], Double.NaN);
}
return binomialTopDown(N, k, p, cache);
}
// More efficient
private static double binomialTopDown(int N, int k, double p, double[][] cache)
{
if ((N == 0) && (k == 0))
{
return 1.0;
}
else if ((N < 0) || (k < 0))
{
return 0.0;
}
else if (Double.isNaN(cache[N][k]))
{
cache[N][k] = (1.0 - p) * binomialTopDown(N - 1, k, p, cache) + p * binomialTopDown(N - 1, k - 1, p, cache);
}
return cache[N][k];
}
The trick is actually to use the bottom-up approach (also called tabulation) to order the computations in an much more efficient way. This is usually achieved by using an iterative version of the algorithm above.
// Much more efficient
private static double binomialBottomUp(int N, int k, double p)
{
/*
double[][] cache = new double[N + 1][k + 1];
cache[0][0] = 1.0;
for (int i = 1; i <= N; i++)
{
cache[i][0] = Math.pow(1.0 - p, i);
for (int j = 1; j <= k; j++)
{
cache[i][j] = p * cache[i - 1][j - 1] + (1.0 - p) * cache[i - 1][j];
}
}
return cache[N][k];
*/
// Optimization using less memory, swapping two arrays
double[][] cache = new double[2][k + 1];
double[] previous = cache[0];
double[] current = cache[1];
double[] temp;
previous[0] = 1.0;
for (int i = 1; i <= N; i++)
{
current[0] = Math.pow(1.0 - p, i);
for (int j = 1; j <= k; j++)
{
current[j] = p * previous[j - 1] + (1.0 - p) * previous[j];
}
temp = current;
current = previous;
previous = temp;
}
return previous[k];
}
Which is the most efficient way to do it using dynamic programming with the Bottom Up approach.
Hope this helps.