动态规划问题


动态规划问题,



package com.dong.alg.dp;

/**
 * 求连续子数组的最大和
 * @author cuihd
 *
 */
public class MaxSumOfSubArray {

	public static void main(String[] args) {
		int[] array = {1,3,-4,7,0,-1,2};
		int result = getMaxSumOfSubArray(array);
		System.out.println(result);
	}
	
	public static int getMaxSumOfSubArray(int[] array) {
		
		if(null == array) {
			throw new NullPointerException("参数array为null");
		} else if(array.length <=0){
			throw new RuntimeException("参数array为的size为0");
		}
		
		int result = array[0];
		int	sum = array[0];
		
		for(int i=1;i<array.length;i++) {
			if(sum > 0) {
				sum = sum + array[i];
			} else {
				sum = array[i];
			}
			
			if(sum > result) {
				result = sum;
			}
		}
		return result;
	}
}


package com.dong.alg.dp;

/**
 * 求最长公共子串(字串为连续的)
 *	http://www.cnblogs.com/dartagnan/archive/2011/10/06/2199764.html
 */
public class MaxSubArray {

	public static void main(String[] args) {

		int[] tr = {1,2,3,4,7,9};
		int[] td = {2,1,3,4,6,9,0,1,2,3,4};
		
		int[] result = getMaxSubArray(tr,td);
		if(null != result) {
			for(int i : result) {
				System.out.print(" " + i);
			}
		}
	}
	
	
	/**
	 * 把一个数组横向铺好,另一个数组纵向铺好,
	 * 然后在相等的元素上面做标记,连续时间最长的对角线就是最长的公共字串
	 * 	1 2 3 4 7 9
	 * 
	 2  0 1 0 0 0 0
 	 1	1 0 0 0 0 0
 	 3	0 0 1 0 0 0
 	 4	0 0 0 2 0 0
 	 6	0 0 0 0 0 0
 	 9	0 0 0 0 0 1
 	 0	0 0 0 0 0 0
 	 1	1 0 0 0 0 0
 	 2	0 2 0 0 0 0
 	 3	0 0 3 0 0 0
 	 4	0 0 0 4 0 0

	 * 
	 * @param tr	需要横向铺的数组
	 * @param td	需要纵向铺的数组
	 * @return
	 */
	public static int[] getMaxSubArray(int[] tr,int[] td) {
		int[] result = null;
		
		int trLength = tr.length;
		int tdlength = td.length;
		
		int maxno = 0;				//记录改公共字串的长度
		int hangposition = -1;		//记录数组td的位置,该位置为最长公共子串的最后一个元素
		int lieposition = -1;		//记录数组tr的位置,该位置为最长公共子串的最后一个元素
		
		//注意,这里比较爱出错。纵向数组为二维数组的总行数,横向数组为二维数组的总列数
		int[][] twodArray = new int[tdlength][trLength];
		System.out.println("二维数组为: " + tdlength + "行" + trLength + "列");
		for(int i = 0;i<tdlength;i++) {
			for(int j=0;j<trLength;j++) {
				if(tr[j] == td[i]) {
					if(j-1 >= 0 && i-1>=0) {
						twodArray[i][j] = twodArray[i-1][j-1] + 1;
						if(twodArray[i][j] > maxno) {
							maxno = twodArray[i][j];
							hangposition = i;
							lieposition = j;
						}
					} else {
						twodArray[i][j] = 1;
					}
				}
			}
		}
		
		//着行打印二维数组
		for(int i = 0;i<tdlength;i++) {
			for(int j=0;j<trLength;j++) {
				System.out.print(" " + twodArray[i][j]);
			}
			System.out.println();
		}
		
		System.out.println(lieposition);
		result = new int[maxno];
		for(int i = lieposition - (maxno-1);i<=lieposition;i++) {
			result[i] = tr[i];
		}
		return result;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值