[leetcode]Minimum Path Sum 最小路径和
2014-03-12 10:11
381 查看
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
这是个典型的dp问题,先初始化第一行,第一列,因为这两行的点如果到达,那只有一个走法,要不一直往右走,要不一直往下走。
而其他的点确可以有2种走法,那么。。又是2种的问题,要么下要么右,不用dp就是等抽
public int minPathSum(int[][] grid) {
if(grid.length==0) return 0;
int numOfRow=grid.length;
int numOfCol=grid[0].length;
for(int col=1;col<numOfCol;col++){
grid[0][col]=grid[0][col-1]+grid[0][col];
}
for(int row=1;row<numOfRow;row++){
grid[row][0]=grid[row-1][0]+grid[row][0];
}
for(int row=1;row<numOfRow;row++){
for(int col=1;col<numOfCol;col++){
grid[row][col]=grid[row][col]+Math.min(grid[row-1][col],grid[row][col-1]);
}
}
return grid[numOfRow-1][numOfCol-1];
}
Note: You can only move either down or right at any point in time.
这是个典型的dp问题,先初始化第一行,第一列,因为这两行的点如果到达,那只有一个走法,要不一直往右走,要不一直往下走。
而其他的点确可以有2种走法,那么。。又是2种的问题,要么下要么右,不用dp就是等抽
public int minPathSum(int[][] grid) {
if(grid.length==0) return 0;
int numOfRow=grid.length;
int numOfCol=grid[0].length;
for(int col=1;col<numOfCol;col++){
grid[0][col]=grid[0][col-1]+grid[0][col];
}
for(int row=1;row<numOfRow;row++){
grid[row][0]=grid[row-1][0]+grid[row][0];
}
for(int row=1;row<numOfRow;row++){
for(int col=1;col<numOfCol;col++){
grid[row][col]=grid[row][col]+Math.min(grid[row-1][col],grid[row][col-1]);
}
}
return grid[numOfRow-1][numOfCol-1];
}
相关文章推荐
- [LeetCode] Minimum Path Sum 最小路径和
- LeetCode(Minimum Path Sum) 找到路径中和最小的
- LeetCode—Minimum Path Sum 二维数组最小路径,动态规划
- Leetcode:Minimum Path Sum 最小路径和
- leetcode64-Minimum Path Sum(最小路径和)
- [置顶] LeetCode--Minimum Path Sum (最小路径和)Python
- [Leetcode] minimum path sum 最小路径和
- 【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】
- LeetCode | Minimum Path Sum(最小路径和)
- [Leetcode-64]Minimum Path Sum 二维数组路径最小和
- Leetcode-64_. Minimum Path Sum(最小路径和)—动态规划解法+记忆化搜索解法-C++解
- [leetcode 64] Minimum Path Sum------从左上角到右下角的最小路径值
- 【LeetCode-面试算法经典-Java实现】【064-Minimum Path Sum(最小路径和)】
- 动态规划--最小路径和(Minimum Path Sum)
- Leet Code 64 Minimum Path Sum - 最小路径和 - Java
- LeetCode:Minimum Path Sum(网格最大路径和)
- LinCode Minimum Path Sum 最小路径和
- Minimum Path Sum最小路径和算法详解
- leetcode:Minimum Path Sum(路线上元素和的最小值)【面试算法题】
- leetcode:Minimum Path Sum(路线上元素和的最小值)【面试算法题】