[Leetcode] Minimum Path Sum
来源:互联网 发布:2016淘宝店铺重开技术 编辑:程序博客网 时间:2024/04/29 21:52
题目:
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,对于某个位置,只可能是由上或者由左到达,因此选取这两个路径中较小的那个。
class Solution {public: int minPathSum(vector<vector<int> > &grid) { if (grid.size() <= 0) return 0; int width = (int)grid.size(); int length = (int)grid[0].size(); vector<vector<int>> dist(width, vector<int>(length, 0)); dist[0][0] = grid[0][0]; for (int i = 1; i < width; ++i) { dist[i][0] = dist[i-1][0] + grid[i][0]; } for (int j = 1; j < length; ++j) { dist[0][j] = dist[0][j-1] + grid[0][j]; } for (int i = 1; i < width; ++i) { for (int j = 1; j < length; ++j) { dist[i][j] = (dist[i-1][j] < dist[i][j-1] ? dist[i-1][j] : dist[i][j-1]) + grid[i][j]; } } return dist[width-1][length-1]; }};
总结:复杂度为O(mn).
0 0
- LeetCode: Minimum Path Sum
- LeetCode Minimum Path Sum
- LeetCode : Minimum Path Sum
- [Leetcode] Minimum Path Sum
- [LeetCode] Minimum Path Sum
- [Leetcode] Minimum Path Sum
- [LeetCode]Minimum Path Sum
- [leetcode]Minimum Path Sum
- LeetCode-Minimum Path Sum
- [leetcode] Minimum Path Sum
- LeetCode - Minimum Path Sum
- LeetCode:Minimum Path Sum
- leetcode minimum path sum
- 【leetcode】Minimum Path Sum
- 【LeetCode】Minimum Path Sum
- Leetcode: Minimum Path Sum
- Leetcode Minimum Path Sum
- LeetCode Minimum Path Sum
- Android ActionBar完全解析,使用官方推荐的最佳导航栏(下)
- HDOJ 1495 非常可乐
- mysql相关命令
- How to use Objective-C on Window
- 第一章 绪论 思维导图
- [Leetcode] Minimum Path Sum
- 很不错的memcached 入门指导资料
- 判断是否开启定位服务的方法
- C++判断字符与数字,按下esc键退出esc
- 第三次自考总结——时间管理和学习知识
- java集合练习笔记
- 真实网络环境下使用易邮搭建网络邮件服务器并测试通过
- 关于点击电源按钮的时候出现了这情况Transport (VMDB) error -44: Message.
- Struts2文件上传