# [LeetCode] 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:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.


Example 2:

Input: grid = [[1,2,3],[4,5,6]]
Output: 12

Constraints:

• m == grid.length
• n == grid[i].length
• 1 <= m, n <= 200
• 0 <= grid[i][j] <= 200

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
dp[0][1] = dp[1][0] = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
dp[i][j] = grid[i - 1][j - 1] + min(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
}
};

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
vector<int> dp(n, INT_MAX);
dp[0] = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (j == 0) dp[j] += grid[i][j];
else dp[j] = grid[i][j] + min(dp[j], dp[j - 1]);
}
}
return dp[n - 1];
}
};

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[i].size(); ++j) {
if (i == 0 && j == 0) continue;
if (i == 0) grid[0][j] += grid[0][j - 1];
else if (j == 0) grid[i][0] += grid[i - 1][0];
else grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid.back().back();
}
};

class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[i].size(); ++j) {
if (i == 0 && j == 0) continue;
int up = (i == 0) ? INT_MAX : grid[i - 1][j];
int left = (j == 0) ? INT_MAX : grid[i][j - 1];
grid[i][j] += min(up, left);
}
}
return grid.back().back();
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/64

Unique Paths

Dungeon Game

Cherry Pickup

Minimum Path Cost in a Grid

Maximum Number of Points with Cost

Minimum Cost Homecoming of a Robot in a Grid

Paths in Matrix Whose Sum Is Divisible by K

Check if There is a Path With Equal Number of 0's And 1's

Minimum Cost of a Path With Special Roads

https://leetcode.com/problems/minimum-path-sum/

https://leetcode.com/problems/minimum-path-sum/discuss/23457/C%2B%2B-DP

https://leetcode.com/problems/minimum-path-sum/discuss/23617/C%2B%2B-solution-beat-98.59

https://leetcode.com/problems/minimum-path-sum/discuss/23611/My-Java-clean-code-DP-no-extra-space

https://leetcode.com/problems/minimum-path-sum/discuss/23678/C%2B%2B-easy-solution-using-dp.-space-compexity-%3A-O(1)

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2015-03-20 11:50  Grandyang  阅读(17545)  评论(4编辑  收藏  举报