leetcode 064 Minimum Path Sum
2016-05-01 19:57
330 查看
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.
Subscribe to see which companies asked this question
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size(), m = 0;
if(n == 0) return 0;
m = grid[0].size();
vector<int> cur(m, -1);
//dp[i][j] = min(dp[i-1][j],dp[i][j-1])+mat[i][j];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(j>=1 && cur[j]!=-1) {
cur[j] = min(cur[j-1], cur[j])+grid[i][j];
} else if(j==0) {
if(cur[j]==-1)
cur[j] = grid[i][j];
else
cur[j] = cur[j]+grid[i][j];
} else if(cur[j]==-1) {
cur[j] = cur[j-1]+grid[i][j];
}
}
}
return cur[m-1];
}
};
Note: You can only move either down or right at any point in time.
Subscribe to see which companies asked this question
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size(), m = 0;
if(n == 0) return 0;
m = grid[0].size();
vector<int> cur(m, -1);
//dp[i][j] = min(dp[i-1][j],dp[i][j-1])+mat[i][j];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(j>=1 && cur[j]!=-1) {
cur[j] = min(cur[j-1], cur[j])+grid[i][j];
} else if(j==0) {
if(cur[j]==-1)
cur[j] = grid[i][j];
else
cur[j] = cur[j]+grid[i][j];
} else if(cur[j]==-1) {
cur[j] = cur[j-1]+grid[i][j];
}
}
}
return cur[m-1];
}
};
相关文章推荐
- HDU1272-小希的迷宫
- 调用QQ截图
- 学习进度条 第九周
- 算法的艺术
- Django build_in 登录注册模块 注销时页面是admin模块自带的注销页面的原因
- lightoj - 1414 February 29
- 冲刺9
- leetcode 之Remove Duplicates from Sorted Array(1)
- 深入理解Java内存模型——final
- FACTORY METHOD(工厂模式)
- 三四月找实习总结
- 个人冲刺06
- HDU 4709:Herding
- KindlePW3壁纸越狱设置问题
- Leetcode 15. 3Sum
- rt3070无线网卡工作在AP模式----fl2440开发板
- QDialog 添加最大化、最小化按钮和关闭按钮,并且要正常显示
- opencv异常提示之 npoints2 >= 0 || npoints3 >= 0 in fitLine
- 《机器学习实战》学习笔记——第3章 决策树
- java如何获取其它用户登录的真是IP地址