代码改变世界

动态规划--合并石子

2018-10-29 16:17  muamaker  阅读(907)  评论(0编辑  收藏  举报

 

动态规划: 

  minx[i][j]  记录着  从第 i 堆到第 j 堆的合并最小花费,令 minx[i][j] = 0;

      sum[i] 为前 i 堆石子数量的总和  sum[0] = 0;

    

1、假如 i 和  j 中间存在 k  使得  minx[i][j] > minx[i][k] + minx[k+1][j] + sum[j] - sum[i-1];   i <= k < j;

  则   minx[i][j] = minx[i][k] + minx[k+1][j] + sum[j] - sum[i-1];

   

 i = 1, j =2; k = 1;

minx[1][2] = minx[1][1] + minx[2][2] + sum[2] - sum[0] = 13;

i = 1, j = 3 ; k = 1、2;

...

	//动态规划--石子
	
	function straight(arr){
		arr.unshift(0);
		var n = arr.length+1;
		var sum = []; // i 为前 i项的石子数和  sum[0] = 0;  sum = [0,5,13,19,28,30,33];
		var minx = [];
		
		//初始化
		sum[0] = 0;
		for(var i = 1 ;  i <= n; i++){
			minx[i] = [];
			minx[i][i] = 0;
		
			sum[i] = sum[i-1] + arr[i];
			
		}
		
		//枚举
		for(var v = 2; v <= n; v++ ){
			for(var i = 1; i <= n-v-1; i++){ //起点
				var j = i + v - 1; //终点
				console.log(i,j)
				minx[i][j] = Infinity; //初始化
				var temp = sum[j] - sum[i-1];
				for(var k = i; k < j; k++ ){
					minx[i][j] = Math.min(minx[i][j],minx[i][k] + minx[k+1][j] + temp);
				}
			}
		}
		
		console.log(minx);
		
		return minx[1][n-2];
	}
		
	console.log(straight([5,8,6,9,2,3]));