个人记录-LeetCode 64. Minimum Path Sum
2016-12-30 19:40
453 查看
问题:
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.
问题的思路与Unique Paths和Unique Paths II一致。
唯一不同的是,每个位置保留的结果不再是到达该位置的走法,而是到达该位置最小的sum。
代码示例:
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.
问题的思路与Unique Paths和Unique Paths II一致。
唯一不同的是,每个位置保留的结果不再是到达该位置的走法,而是到达该位置最小的sum。
代码示例:
public class Solution { public int minPathSum(int[][] grid) { if (grid == null || grid.length < 1 || grid[0].length < 1) { return 0; } int m = grid.length; int n = grid[0].length; //初始化 //由于参数数组中也可以含有0,因此边缘初始化为-1 int[][] rst = new int[m+1][n+1]; for (int i = 0; i <= m; ++i) { rst[i][0] = -1; } for (int j = 0; j <= n; ++j) { rst[0][j] = -1; } for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { //第一个位置 if (i == 1 && j == 1) { rst[1][1] = grid[0][0]; continue; } //特殊处理第1行和第1列 if (rst[i][j-1] == -1) { rst[i][j] = rst[i-1][j] + grid[i-1][j-1]; } else if (rst[i-1][j] == -1){ rst[i][j] = rst[i][j-1] + grid[i-1][j-1]; } else { //其它位置,等于当前位置的值,与min(前一列,上一行)的和 rst[i][j] = grid[i-1][j-1] + (rst[i-1][j] > rst[i][j-1] ? rst[i][j-1] : rst[i-1][j]); } } } return rst[m] ; } }
相关文章推荐
- LeetCode --- 64. Minimum Path Sum
- [Leetcode]@python 64. Minimum Path Sum
- leetcode 64. Minimum Path Sum
- leetcode No64. Minimum Path Sum
- Leetcode 64. Minimum Path Sum (Medium) (cpp)
- 【LeetCode】64. Minimum Path Sum
- [leetcode] 64. Minimum Path Sum
- leetcode 64. Minimum Path Sum-最小路径和|动态规划
- LeetCode 64. Minimum Path Sum(最小路径和)
- 个人记录-LeetCode 1.Two Sum
- LeetCode 64. Minimum Path Sum
- [leetcode] 64. Minimum Path Sum
- leetcode 64. Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- 【leetcode】64. Minimum Path Sum
- [Leetcode] 64. Minimum Path Sum
- [LeetCode]64. Minimum Path Sum
- LeetCode *** 64. Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- 个人记录-LeetCode 2.Add Two Numbers