Given a non-negative integer of mxn 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 的总和最小。
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/minimum-path-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
The complete code
Using the results of running overtime thinking back, a total of 61 test cases, only 60 passed.
Despite all conceivable pruning shears, so I really can not think of how to optimize.
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size() == 0)
return 0;
int res = INT_MAX;
path(grid, res, 0, 0, 0);
return res;
}
private:
void path(vector<vector<int>>& grid, int &res, int cur, int i, int j){
if(i == grid.size() - 1 && j == grid[0].size() - 1){
cur += grid[i][j];
if(cur < res)
res = cur;
return;
}
int temp;
temp = cur + grid[i][j];
//向下走
if(i + 1 < grid.size() && temp < res)
path(grid, res, temp, i + 1, j);
//向右走
if(j + 1 < grid[0].size() && temp < res)
path(grid, res, temp, i, j+1);
}
};
Dynamic Programming
In fact, this question is a typical topic of dynamic programming, backtracking blame too familiar with the
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size() == 0)
return 0;
int res = INT_MAX;
path(grid, res, 0, 0, 0);
return res;
}
private:
void path(vector<vector<int>>& grid, int &res, int cur, int i, int j){
if(i == grid.size() - 1 && j == grid[0].size() - 1){
cur += grid[i][j];
if(cur < res)
res = cur;
return;
}
int temp;
temp = cur + grid[i][j];
//向下走
if(i + 1 < grid.size() && temp < res)
path(grid, res, temp, i + 1, j);
//向右走
if(j + 1 < grid[0].size() && temp < res)
path(grid, res, temp, i, j+1);
}
};
执行结果:通过
显示详情
执行用时 :12 ms, 在所有 C++ 提交中击败了57.07%的用户
内存消耗 :11 MB, 在所有 C++ 提交中击败了45.90%的用户