LeetCode-62: Problems and minimum path
First, the subject description:
Given a non-negative integer m * n
grid grid
, find a path from left to bottom right, so that the sum of the minimum number of paths.
Note: you can only move one step down or to the right.
Example:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
Second, the problem-solving ideas:
The entitled typical dynamic programming problem. Three steps to solve the problem
1. Define the meaning of the array elements
Here we can define a two-dimensional array dp[][]
, dp[i][j]
used to indicate when the end point coordinates
, we hope the answer, that is the shortest path to the coordinates.
2. Find the iterative relationship between the array elements relationship
For example, we now have to consider how many get this X is due only to the right path or down, then we arrive X
there are two ways of
- From 2 to go to the right step to reach X
- 4 down the road from one step to reach X
Previous we said, dp[i][j]
used to indicate when the end point coordinates
, the shortest path to our requirements. Then the arrivalX
path length needed to have two results:
- From 2 to reach the right:
2 + X点的值
, 7 - Down to from 4:
4+ X点的值
, 9
Maybe the result of the election which it obviously choose small, that is 7.
3. Define boundary conditions
The initial value is very important to determine the subsequent steps can get the right result, the initial value of what is it? I.e. rainbow colored portion shown below:
4. The matrix obtained dp
Obviously, the lower right corner of that element is a two-dimensional array dp we ask for explanations
Tidy Code
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
/*数据不对直接跑路*/
auto m = grid.size();
auto n = grid[0].size();
if(m <= 0 || n <= 0) return 0;
int dp[m][n];
/*定义彩虹色部分的初始值(第1列)*/
long sum = 0;
for(int i = 0; i < m; i++){
dp[i][0] = sum + grid[i][0];
sum += grid[i][0];
}
/*定义彩虹色部分的初始值(第1行)*/
sum = 0;
for(int i = 0; i < n; i++){
dp[0][i] = sum + grid[0][i];
sum += grid[0][i];
}
/*计算*/
for(int i = 1; i < m; i++)
for(int j = 1; j < n; j++)
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
return dp[m - 1][n - 1];
}
};
Operating results
do not know why
spatial complexity may further memory 100%