Leetcode 题解系列(八)
2017-11-05 23:53
375 查看
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→1minimizes the sum.
题目分析
暴力解法一个格子可以从上面个格子走来,也可以从左边的格子走来,如果是N∗N地图,共有2N−1中选择。
动态规划
由于上一个点只能是上方或者左方的格子,那么到达该格子的最短路径即使从两个方向来的最短的一个。即是,distance[i][j]=min(from[i−1][j],from[i][j−1])
初始状态:起点的距离为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]; } };
相关文章推荐
- Leetcode 题解系列(三)
- LeetCode题解系列--4. Median of Two Sorted Arrays
- Leetcode 题解系列(十四)
- Leetcode 题解系列(十)
- LeetCode题解系列--123. Best Time to Buy and Sell Stock III
- LeetCode题解系列--763. Partition Labels
- LeetCode题解系列--684. Redundant Connection
- Leetcode 题解系列(十一)
- Leetcode 系列题解(十八)
- LeetCode题解系列--1. Two Sum
- Leetcode 题解系列(十二)
- Leetcode 题解系列(六)
- LeetCode题解系列--121. Best Time to Buy and Sell Stock
- LeetCode题解系列--309. Best Time to Buy and Sell Stock with Cooldown
- LeetCode题解系列--685. Redundant Connection II
- Leetcode 题解系列(七)
- LeetCode题解系列--712. Minimum ASCII Delete Sum for Two Strings
- LeetCode题解系列--122. Best Time to Buy and Sell Stock II
- LeetCode题解系列--5. Longest Palindromic Substring
- Leetcode 题解系列(四)