62. Unique Paths
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?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
解析
从矩阵的左上角走到左下角有多少种走法。
参考答案
自己写的(递归搜索):
class Solution {
public int uniquePaths(int m, int n) {
return backTrack(m-1, n-1, 0);
}
public int backTrack(int m, int n, int count) {
int t = count;
if (m == 0 && n == 0) {
return t + 1;
}
if (m > 0) {
t += backTrack(m-1, n, count);
}
if (n > 0) {
t += backTrack(m, n-1, count);
}
return t;
}
}
动态规划:
public class Solution {
public int uniquePaths(int m, int n) {
int[] arr = new int[m];
for (int i = 0; i < m; i++) {
arr[i] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
arr[j] = arr[j] + arr[j-1];
}
}
return arr[m-1];
}
}
递归搜索会有大量重复搜索的过程,动态规划只需要遍历整个二维数组,计算出起点到每个点的路径数就能得到起点到终点的路径数。
已知条件有:
每个点的路径数等于它左边的路径数加上上边的路径数;
起点到第零列的路径数为1;
起点到第零行的路径数为1;
从这些已知条件出发就可以算出所有点的路径数,从而得到终点的路径数。