public class Dynamic_Programming {
public static int HowManyWays(int n)
{
int [] mem = new int[]{0,1};
for(int i = 2; i <= n; i++)
{
int sum = 0;
for(int k =1; k <= n-1; k++)
{
sum += mem[k]*mem[n-k];
}
mem[i] = sum;
}
return mem[n];
}
public static void main (String [] args)
{
long startTime = System.nanoTime();
System.out.println("For 2 matracies: " + HowManyWays(2));
long totalTime = System.nanoTime()-startTime;
System.out.println("Time in nanoseconds: " + totalTime);
}
}
This is the code for a simple method that uses the dynamic programming technique in order to determine the number of ways to multiply n matrices together. However I keep getting and ArrayIndexOutOfBounds
error when I run the program. It tells me that the problem is with this line of code right here. mem[i] = sum;
. Some guidance on how to fix this problem would be greatly appreciated.