title: Error with matrices and array index out of bounds
body: <p>So, i need to implement this code that will return me the best solution of parentheses from a multiplication of matrices in java. I made a function for the printing of "(" ")" and in the main i did the construction of the matrices M and S for the resolution (dinamic programming).
  i keep getting this error after it prints the first "(":</p>
  
  <hr>
  
  <pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
      at ProgramacaoDinamica.parenterizacao(ProgramacaoDinamica.java:13)
      at ProgramacaoDinamica.main(ProgramacaoDinamica.java:46)
  </code></pre>
  
  <hr>
  
  <p>code:</p>
  
  <pre><code>public class ProgramacaoDinamica {
      private static int[][] s;
  
      public static void parenterizacao(int[][] s, int i, int j) {
          if (i == j) {
              System.out.println("M" + i);
          } else {
              System.out.println("(");
              parenterizacao(s, i, s[i][j]);
              parenterizacao(s, s[i][j] + 1, j);
              System.out.println(")");
          }
      }
  
      public static void main(String[] args) {
  
          int[] p = {15, 5, 10, 20, 25}; //VETOR P DO ENUNCIADO (alteracoes aqui!!!)
  
          int n = p.length - 1;
  
  
          int[][] m = new int[n][n];
          int[][] s = new int[n - 1][n - 1];
  
          for (int i = 0; i &lt; n; i++) {
              m[i][i] = 0;
          }
  
          for (int l = 1; l &lt; n; l++) {
              for (int i = 1; i &lt;= l - n + 1; i++) {
                  int j = i + l - 1;
                  m[i][j] = 9999;
                  for (int k = i; k &lt;= j - 1; k++) {
                      int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
                      if (q &lt; m[i][j]) {
                          m[i][j] = q;
                          s[i][j] = k;
                      }
                  }
              }
          }
          parenterizacao(s, 1, n);
      }
  
  }
  </code></pre>
  
  <p>can anyone help me out with this? im starting to get lost with the code?
  im following this semi codes:
  <a href="http://oi60.tinypic.com/xnyq2s.jpg" rel="nofollow">java1</a>
  <a href="http://oi58.tinypic.com/s68276.jpg" rel="nofollow">java2</a></p>