题目传送地址: ​​https://leetcode.cn/problems/unique-paths/​

运行效率:

Leetcode62. 不同路径_算法


代码如下:

public static int uniquePaths(int m, int n) {
HashMap<String, Integer> map = new HashMap<>();
int i = uniqPathsWithMap(m, n, map);
return i;
}

public static int uniqPathsWithMap(int m, int n, HashMap<String, Integer> map) {
String key = m + ":" + n;
//使用map,提升运行性能
if (map.containsKey(key)) {
return map.get(key);
}
//处理边界情况
if (m == 1 || n == 1) {
return 1;
}
//要想走到(m,n)位置坐标,有2种可能,第一种是从(m-1,n)到(m,n), 第2种是从(m,n-1)到(m,n)
int i = uniqPathsWithMap(m - 1, n, map) + uniqPathsWithMap(m, n - 1, map);
map.put(m + ":" + n, i);
return i;
}