矩阵连乘问题的非动态解法
2012-10-26 18:02
465 查看
前几天又看了看王晓东的计算机算法设计与分析,今天写了一个递归调用写法可以很清晰的显示重复计算的部分,而且算法也容易理解
这里没有做动态规划算法的实现,实现动态规划只需要把递归计算的结果保存下来避免重复计算就可以了
这里没有做动态规划算法的实现,实现动态规划只需要把递归计算的结果保存下来避免重复计算就可以了
package com.popo.matrix; public class Matrix { private int row; private int list; private static int len; public Matrix(int row, int list) { super(); this.row = row; this.list = list; } public static void main(String[] args) { Matrix[] matrixs= new Matrix[]{new Matrix(5, 4),new Matrix(4, 3),new Matrix(3, 6),new Matrix(6, 2),new Matrix(2, 8)}; len=matrixs.length; int best =getTheBestMutiply(matrixs, 0, len-1); System.out.println("the best is "+best); } public static int getTheBestMutiply(Matrix[] matrixs,int from,int to){ int best=-1; int p = 0; if(from<0||to>=len){ return -1; } if(from==to){ return 0; } if(from+1==to){ return matrixs[from].row*matrixs[from].list*matrixs[to].list; } //求从form 到 to的最优解 for(int i=from;i<to;i++){ //显示重复计算的部分 System.out.println("count "+ from +" to "+i+", and "+(i+1)+" to "+to); //这里是递归调用 int thissum = getTheBestMutiply(matrixs,from,i)+getTheBestMutiply(matrixs,i+1,to)+(matrixs[from].row)*matrixs[i].list*matrixs[to].list; if(best<0||thissum<best){ best=thissum; p=i; } } // System.out.println(from+" to "+ to+" the best devider p is "+p+" ,"+best+"\n"); return best; } }