简单的动态规划,直接走就行了,
第一行的数据只能右边走所以数据只跟左边的数据有关
第一列的数据只能从上面往下走,只跟上面数据有关
其他的方面可以来自三个方向,上面,下面,左上
public class Solution {
/**
*
* @param presentVolumn int整型二维数组 N*M的矩阵,每个元素是这个地板砖上的礼物体积
* @return int整型
*/
public int selectPresent (int[][] presentVolumn) {
// write code here
int N=presentVolumn.length;
if(N==0) return 0;
int M=presentVolumn[0].length;
for(int row=0;row<N;row++){
for (int col=0;col<M;col++){
//Default state
if(row==0&&col==0) continue;
//第一行的只能左边来
if(row==0)
presentVolumn[row][col]+=presentVolumn[row][col-1];
//第一列只能上面来
if(col==0)
presentVolumn[row][col]+=presentVolumn[row-1][col];
//其他方式有两种 从左上
if(col!=0&&row!=0){
presentVolumn[row][col]+=Math.min(Math.min(presentVolumn[row-1][col],presentVolumn[row][col-1]),presentVolumn[row-1][col-1]);
}
}
}
return presentVolumn[N-1][M-1];
}
}
京公网安备 11010502036488号