LeetCode 0064 - Minimum Path Sum
# Hints
- DP
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Medium |
Given a 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:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
# 题意
给定一个 的矩阵,从 出发只能前往 或 ,求从 到 的路径中,路径上所有数之和的最小值。
# 题解
考虑动态规划,设 表示从 到 的最小路径和。
状态转移方程:
则 即为答案。时间复杂度为 。
细节问题:
- 注意特判空矩阵。
# AC代码
class Solution {
public:
int minPathSum(vector<vector<int>> & grid) {
// 特判
if (grid.empty() || grid.front().empty()) {
return 0;
}
// 初始化
int m = grid.size(), n = grid.front().size();
int dp[m][n];
// 递推
dp[0][0] = grid[0][0];
for (int i = 1; i < m; i ++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
for (int j = 1; j < n; j ++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
for (int i = 1; i < m; i ++) for (int j = 1; j < n; j ++) {
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
// 返回
return dp[m - 1][n - 1];
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01