动态规划之矩阵连乘

动态规划的关键是建立最优子结构,明确什么是需要存储的中间结果。

另: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]);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值