程序碎片- 矩阵乘法优化(dp,循环)

下班了换个eclipse写写,感觉还蛮好的。

这个循环的原理是,沿着矩阵的对角线,一层层向上计算,

发现这样的过程中,前面的条件都已经算好了。所以就不用递归了。

import java.util.ArrayList;

 

public class MatrixMultiply {

    public MatrixMultiply() {

       Matrix m1 = new Matrix(2, 5);

       Matrix m2 = new Matrix(5, 100);

       Matrix m3 = new Matrix(100, 4);

       Matrix m4 = new Matrix(4, 50);

       Matrix m5 = new Matrix(50, 6);

       MList .add(m1);

       MList .add(m2);

       MList .add(m3);

       MList .add(m4);

       MList .add(m5);

       for ( int i = 0; i < 5; i++)

           for ( int j = 0; j < 5; j++) {

              if (i >= j)

                  M [i][j] = 0;

              else

                  M [i][j] = Integer. MAX_VALUE ;

           }

    }

 

    private int [][] M = new int [5][5];

    private ArrayList<Matrix> MList = new ArrayList<Matrix>();

 

    public void getResult() {

       // already fill the left-below half of the matrix, now fill the left-up

       // part, the specialIndex is build by analysis matrix's structure

       for ( int specialIndex = 1; specialIndex < 5; specialIndex++) {

           int xIndex = 0;

           int yIndex = xIndex + specialIndex;

           while (yIndex < 5) {

              M [xIndex][yIndex] = getMax(xIndex, yIndex);

              yIndex++;

              xIndex++;

           }

       }

       System. out .println( "the optimized result is :" + M [0][4]);

    }

 

    private int getMax( int xIndex, int yIndex) {

       if ( M [xIndex][yIndex] != Integer. MAX_VALUE )

           return M [xIndex][yIndex];

       else {

           int finalMin = Integer. MAX_VALUE ;

           int tempMin;

           for ( int k = xIndex; k < yIndex; k++) {

              tempMin = M [xIndex][k] + M [k + 1][yIndex]

                     + MList .get(xIndex). orderX * MList .get(k). orderY

                     * MList .get(yIndex). orderY ;

              if (finalMin > tempMin)

                  finalMin = tempMin;

           }

           return finalMin;

       }

    }

 

    class Matrix {

       public Matrix( int x, int y) {

           orderX = x;

           orderY = y;

       }

 

       int orderX ;

       int orderY ;

    }

 

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值