题目要求:
相比较于unique path,寻找一条最短路径,仍然采用动态规划:
Method: flag[i][j] = grid[i][j]+(flag[i-1][j] < flag[i][j-1]? flag[i-1][j]:flag[i][j-1]);
源码如下:
class Solution {
public:
void non_uniqpath(vector<vector<int>>& grid,int& num){
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> flag;
flag.resize(m);
for_each(flag.begin(),flag.end(),[n](vector<int>& pa){pa.resize(n,0);});
flag[0][0] = grid[0][0];
for (int i=1;i<n;i++){
flag[0][i] = grid[0][i] + flag[0][i-1];
}
for (int i=1;i<m;i++){
flag[i][0] = grid[i][0] + flag[i-1][0];
}
for (int i=1;i<m;i++){
for (int j=1;j<n;++j){
flag[i][j] = grid[i][j]+(flag[i-1][j] < flag[i][j-1]? flag[i-1][j]:flag[i][j-1]);
}
}
num = flag[m-1][n-1];
}
int minPathSum(vector<vector<int>>& grid) {
int num=0;
non_uniqpath(grid,num);
return num;
}
};
网友评论