动态规划的关键是建立最优子结构,明确什么是需要存储的中间结果。
另:java 中 静态方法只能调用静态变量与静态方法,原因是非静态的变量与方法只存在于定义的对象实例中,在类中是不能使用的。
代码如下:
package javaPractice;
import java.util.Scanner;
public class DpForMatrixMultiplication {
/**
* @param args
* number of matrices
* table for storing the numbers of columns and rows of matrices
* table for storing the minimum number for multiplication
* table for storing the breakpoints
*/
public static int matricesNumber;
public static int[][] t, s, m;
public static int FindBreakpoint(int begin, int end)
{
int breakpoint, temp, min;
if(begin == end)
{
s[begin][end] = 0;
return 0;
}
else if(end - begin == 1)
{
s[begin][end] = begin;
return m[begin][0] * m[end][1] * m[begin][1];
}
else
{
min = m[begin][0] * m[end][1] * m[begin][1] + t[begin+1][end];
breakpoint = begin;
for(int i = 1; i < end - begin; i++)
{
temp = m[begin][0] * m[end][1] * m[begin + i][1] + t[begin][begin + i] + t[begin + i + 1][end];
if(temp < min)
{
min = temp;
breakpoint = begin + i;
}
}
s[begin][end] = breakpoint;
return min;
}
}
public static void printResult(int i, int j)
{
if(i == j)
System.out.print("A" + i);
else
{
System.out.print("(");
printResult(i, s[i][j]);
System.out.print("*");
printResult(s[i][j] + 1, j);
System.out.print(")");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
matricesNumber = scan.nextInt();
m = new int[matricesNumber][2];
s = new int[matricesNumber][matricesNumber];
t = new int[matricesNumber][matricesNumber];
for(int i = 0; i < matricesNumber; i++)
{
m[i][0] = scan.nextInt();
m[i][1] = scan.nextInt();
}
scan.close();
for(int i = 0; i < matricesNumber; i++)
{
for(int j = 0; i + j < matricesNumber; j++)
t[j][j + i] = FindBreakpoint(j, j + i);
}
printResult(0, matricesNumber - 1);
System.out.println("\nthe minimum number of multiplication is " + t[0][matricesNumber - 1]);
}
}