No, the implementation is correct as it is. Change s[i][j] = k; to s[i][j] = k + 1; will break the program.
You can test this by copying the code to the MatrixOrderOptimization.java file and adding a main function like this one:
public static void main(String[] args) { MatrixOrderOptimization moo = new MatrixOrderOptimization(); moo.matrixChainOrder(new int[]{ 3, 2, 4, 3, 2 }); moo.printOptimalParenthesizations(); }
Try to compile and run the program with the proposed change and without it. You will see that making the proposed change leads to invalid index values.
Why is this? Well, the value of the solution s[i][j] is defined as "the index that has reached the optimal cost." This is what he called in pseudocode, and how the Java implementation understands it.
You indicate that in the pseudo-code, the indices begin with 1 and in the Java implementation they begin with 0. However, the value of s[i][j] in both cases is the index that has reached the optimal cost .
If you change the indexes by adding one, you drop the rest of the program. Think of it this way: instead of changing s[i][j] = k; on s[i][j] = k + 1; change the access to the array in printOptimalParenthesizations . On each line where the code refers to s[i][j] , change this to s[i][j]+1 .
In other words, replace
printOptimalParenthesizations(s, i, s[i][j], inAResult); printOptimalParenthesizations(s, s[i][j] + 1, j, inAResult);
from
printOptimalParenthesizations(s, i, s[i][j]+1, inAResult); printOptimalParenthesizations(s, s[i][j]+1 + 1, j, inAResult);
The effect of these changes exactly matches your proposed change. Here we add one to the optimal index when we pull it out of the array, while you suggest adding it to the optimal index when you insert it into the array.
In both cases, the value becomes incorrect, and the program crashes. This is because the value of s[i][j] not an optimal index plus one. This is just an optimal index.
The Java program expects s to contain optimal indices, since it understands optimal indices, which means that they start from scratch. If you change these values by adding them, you violate the value of the indices and break the program.