牛客网—编程题(1)牛牛的礼物

题目描述 众所周知,牛妹有很多很多粉丝,粉丝送了很多很多礼物给牛妹,牛妹的礼物摆满了地板。地板是N\times MN×M的格子,每个格子有且只有一个礼物,牛妹已知每个礼物的体积。地板的坐标是左上角(1,1)右下角(N, M)。牛妹只想要从屋子左上角走到右下角,每次走一步,每步只能向下走一步或者向右走一步或者向右下走一步每次走过一个格子,拿起(并且必须拿上)这个格子上的礼物。牛妹想知道,她能走到最后拿起的所有礼物体积最小和是多少?
示例1
输入: [[1,2,3],[2,3,4]]
输出:7
思路:图示

1 2 3 4
3 2 4 2
2 4 7 6

i-1, j-1 i-1,j
i, j-1 i,j
主要是用来填表。首先可以确定最上边一行,最左边一列,然后i,j主要与左上,上,左三个有关,通过比较进行填充。
代码:

import java.util.*;
public class Solution {
/**
*
* @param presentVolumn int整型二维数组 N*M的矩阵,每个元素是这个地板砖上的礼物体积
* @return int整型
*/
public int selectPresent (int[][] presentVolumn) {
// write code here
if(presentVolumn == null || presentVolumn.length < 1 || presentVolumn[0].length < 1)
return 0;
int m= presentVolumn.length;
int n= presentVolumn[0].length;
int[][] b = new int[m][n];
b[0][0]=presentVolumn[0][0];
for (int i=1; ib[0][i] =b[0][i-1]+presentVolumn[0][i];
} //行填写
for(int i=1; ib[i][0] = b[i-1][0]+presentVolumn[i][0];
} //列填写
【牛客网—编程题(1)牛牛的礼物】for(int j=1; jfor (int i=1; ib[i][j]=min(b[i-1][j],b[i][j-1],b[i-1][j-1]) + presentVolumn[i][j];
}
}
return b[m-1][n-1];
}
public int min(int a, int b,int c) {
int t = a;
if(a>b){
t=b;
}
if(t>c){
t=c;
}
return t;
}
}

    推荐阅读