/*备忘录法。*/
class Solution {
public:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1) return 0;
vector<vector<int> > path(m+1, vector<int>(n+1, 0));
for(int i = 1; i <= m; ++i){
for(int j = 1; j <= n; ++j){
path[i][j] = dfs(i, j, path);
}
}
return path[m][n];
}
int dfs(int row, int col, vector<vector<int> > &path){
if(row == 1 || col == 1) return 1;
else return get(row-1, col, path) + get(row, col-1, path);
}
int get(int row, int col, vector<vector<int> > &path){
if(row == 1 || col == 1) return 1;
if(path[row][col] > 0) return path[row][col];
else return dfs(row, col, path);
}
};
/*动态规划法。*/
class Solution {
public:
int uniquePaths(int m, int n) {
if(m < 1 || n < 1) return 0;
vector<int> path(n+1, 0);
path[1] = 1;
for(int i = 1; i <= m; ++i){
for(int j = 2; j <= n; ++j){
path[j] = path[j] + path[j-1];
}
}
return path[n];
}
};LeetCode之Unique Paths
最新推荐文章于 2019-03-31 14:14:09 发布
本文介绍两种求解网格中从左上角到右下角的不同路径数的方法:备忘录法和动态规划法。备忘录法通过递归加记忆化搜索减少重复计算;动态规划法则利用一维数组存储中间结果,提高空间效率。
464

被折叠的 条评论
为什么被折叠?



