
方法1: recursion+memoization。时间复杂mn,空间复杂mn。
class Solution {
Map<Pair<Integer, Integer>, Integer> map = new HashMap<>();
public int uniquePaths(int m, int n) {
if(m < 1 || n < 1) return 0;
if(m == 1 && n == 1) return 1;
if(map.containsKey(new Pair<>(m, n))) return map.get(new Pair<>(m, n));
int res1 = uniquePaths(m - 1, n);
int res2 = uniquePaths(m, n - 1);
map.put(new Pair<>(m, n), res1 + res2);
return res1 + res2;
}
}
方法2: dp。时间复杂mn,空间复杂mn
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m + 1][n + 1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(i == 1 && j == 1) dp[i][j] = 1;
else dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m][n];
}
}
总结:
- 无
本文介绍了两种方法解决独特路径问题:1. 使用递归结合记忆化搜索,时间复杂度和空间复杂度均为O(mn);2. 应用动态规划,同样以O(mn)的时间和空间复杂度求解。这两种方法都是通过计算网格中从左上角到右下角的不同路径数量来实现的。
1453

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



