Leetcode 题解系列(八)
来源:互联网 发布:网络主播妆容视频教程 编辑:程序博客网 时间:2024/06/02 06:57
64. Minimum Path 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.
Example 1:
[[1,3,1], [1,5,1], [4,2,1]]
Given the above grid map, return 7
. Because the path 1→3→1→1→1
minimizes the sum.
题目分析
暴力解法
一个格子可以从上面个格子走来,也可以从左边的格子走来,如果是
动态规划
由于上一个点只能是上方或者左方的格子,那么到达该格子的最短路径即使从两个方向来的最短的一个。即是,
初始状态:起点的距离为0
实现如下:
class Solution { public: int minPathSum(vector<vector<int>> &grid) { const auto size_r = grid.size(), size_c = grid[0].size(); auto map = vector<vector<int>>(size_r, vector<int>(size_c, 0)); for (int i = 1; i < size_c; ++i) { map[0][i] = map[0][i - 1] + grid[0][i - 1]; } for (int i = 1; i < size_r; ++i) { map[i][0] = map[i - 1][0] + grid[i - 1][0]; for (int j = 1; j < size_c; ++j) { map[i][j] = std::min(map[i - 1][j] + grid[i - 1][j], map[i][j - 1] + grid[i][j - 1]); } } // for (auto& i : map) { // for (auto& j : i) { // std::cout << j << " "; // } // std::cout << std::endl; // } return map[size_r - 1][size_c - 1] + grid[size_r - 1][size_c - 1]; }};
阅读全文
0 0
- Leetcode 题解系列(八)
- Leetcode 题解系列(一)
- Leetcode 题解系列(二)
- Leetcode 题解系列(三)
- Leetcode 题解系列(四)
- Leetcode 题解系列(五)
- Leetcode 题解系列(六)
- Leetcode 题解系列(七)
- Leetcode 题解系列(九)
- Leetcode 题解系列(十)
- Leetcode 题解系列(十一)
- Leetcode 题解系列(十三)
- Leetcode 题解系列(十二)
- LeetCode OJ题解系列
- LeetCode Single Number系列题解
- 列表重新排序——Leetcode系列(八)
- LeetCode题解系列--1. Two Sum
- LeetCode题解系列--5. Longest Palindromic Substring
- 《Comparable接口与Comparator接口的区别》
- 图的基本概念;图的存储表示:邻接矩阵、邻接表
- POJ 1251 Jungle Roads (kruskal)
- SSM:spring+springmvc+mybatis框架中的XML配置文件功能详细解释
- hdu 5971Wrestling Match
- Leetcode 题解系列(八)
- mysql主主同步两个数据库同时写入,实现原理:自动增长主键不重复
- Java String 类
- ElasticSearch5.x踩坑记录(一):windows系统下的ElasticSearch5.6.3及head插件安装
- activemq linux安装与配置
- 探索View的事件分发机制
- 破解webstorm
- 设计模式(1)-单例模式
- C语言的函数指针类型和回调函数-源码