https://www.nowcoder.com/practice/7d21b6be4c6b429bb92d219341c4f8bb?tpId=117&&tqId=35078&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
题目描述
给定一个 n * m 的矩阵 a,从左上角开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,输出所有的路径中最小的路径和。
思路很清晰,很明显的动归,以下先给出一个错误的解法,需引起重视:
public int minPathSum (int[][] matrix) {
// write code here
if(null == matrix){
return 0;
}
int x = matrix.length;
int y = matrix[0].length;
int[][] DP = new int[x+1][y+1];
for(int i = 0; i < x; i++){
for(int j = 0; j < y; j++){
DP[i+1][j+1] = Math.min(DP[i][j+1],DP[i+1][j]) + matrix[i][j];
}
}
return DP[x][y];
}
上述解法看似没问题,DP增加了一行一列来防止溢出的场景,但实际上这样初始化是有问题的。 如当求DP[1][1]的值时,需求DP[0][1]和DP[1][0]的最小值,但因为DP[1][0]是0,所以取的是0,所以答案有误。
正解:
/**
*
* @param matrix int整型二维数组 the matrix
* @return int整型
*/
public int minPathSum (int[][] matrix) {
// write code here
if(null == matrix){
return 0;
}
int x = matrix.length;
int y = matrix[0].length;
int[][] DP = new int[x][y];
DP[0][0] = matrix[0][0];
for(int i = 1; i < x; i++){
DP[i][0] = DP[i-1][0] + matrix[i][0];
}
for(int j = 1; j < y; j++){
DP[0][j] = DP[0][j-1] + matrix[0][j];
}
for(int i = 1; i < x; i++){
for(int j = 1; j < y; j++){
DP[i][j] = Math.min(DP[i-1][j],DP[i][j-1]) + matrix[i][j];
}
}
return DP[x-1][y-1];
}