Minimum Path Sum
2016-06-15 19:46
239 查看
题目描述:
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.
代码如下:
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m]
;
dp[0][0] = grid[0][0];
for(int j = 1;j<n;j++){
dp[0][j] = dp[0][j-1] + grid[0][j];
}
for(int i = 1;i<m;i++){
dp[i][0] = dp[i-1][0] + grid[i][0];
}
for(int j = 1;j<n;j++){
for(int i = 1;i<m;i++){
dp[i][j] = Integer.min(dp[i-1][j],dp[i][j-1])+grid[i][j];
}
}
return dp[m-1][n-1];
}
}
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.
代码如下:
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m]
;
dp[0][0] = grid[0][0];
for(int j = 1;j<n;j++){
dp[0][j] = dp[0][j-1] + grid[0][j];
}
for(int i = 1;i<m;i++){
dp[i][0] = dp[i-1][0] + grid[i][0];
}
for(int j = 1;j<n;j++){
for(int i = 1;i<m;i++){
dp[i][j] = Integer.min(dp[i-1][j],dp[i][j-1])+grid[i][j];
}
}
return dp[m-1][n-1];
}
}
相关文章推荐
- commons-lang工具类用法
- servlet中service doGet doPost 的关系
- 期望dp BZOJ3450+BZOJ4318
- BZOJ NOI十连测 第一测 T1
- 调用系统的分享功能
- 通过跳绳瘦下来是一种怎么样的体验?
- Mat
- 第十六周项目4:阅读下面的程序,指出其功能(3)
- 第十六周项目4:阅读下面的程序,指出其功能(2)
- android 自定义控件(二)
- 程序员的成长和代码行数的关系
- 手机端的轮播效果
- mysql数据库操作语法大全
- Universal-Image-Loader,android-Volley,Picasso、Fresco和Glide五大Android开源组件加载网络图片的优缺点比较
- 差分约束系统
- 第十六周项目4:阅读下面的程序,指出其功能(1)
- JSP中的MIME
- 第十六周项目3:查看下面程序的输出结果,并解释为什么
- 从古希腊神话说起,讲讲英语里的偏旁部首
- Cocos2d-Lua之运算符