方法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];
}
}
总结:
- 无