A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
移动的方向只能是向下,向右。这类的问题,我一般会选择取小一点的数进行模拟。
比如一个2 * 2的 board。
我们假设有一个跟原来board一样大小的数组,用来存储能到达i, j 位置的路径的个数。
当i = 0, j = 0的时候,显然只有一种,
当i = 0, j = 1的时候,只有经过i = 0, j = 0 过来的路径,也是1
当i = 1, j = 0的时候,只有经过i = 0, j = 0的路径,也是1
当i = 1,j = 1的时候,为了走到这个位置,可以从i = 0, j = 1走过来,也可以从i = 1, j = 0走过来。
所以结果是1 + 1 = 2。
再假设我们有一个2 * 3的board。
同样经过先前的模拟,我们可以得到能到达地i, j位置的路径个数。
最后,我们可以得到最终的推导。
1. 到达board x = 0 或 y = 0这些边缘位置的路径的个数是 1。
2. 到达board x > 1且 y > 1这些中间位置的路径的个数是:能到它左边的路径的个数 + 能到它上面的路径的个数。
这就是一个动态规划(dynamic programming)的思路!
运行时间:
代码:
public class UniquePaths {
public int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
int[][] cache = new int[m][n];
//edges cases
for (int i = 0; i < m; i++) {
cache[i][0] = 1;
}
for (int j = 1; j < n; j++) {
cache[0][j] = 1;
}
//border cases
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
cache[i][j] = cache[i][j - 1] + cache[i - 1][j];
}
}
return cache[m - 1][n - 1];
}
}