题目:
机器人位于网格的左上角(下图中标记为“Start”)并试图到达网格的右下角(下图中标记为“Finish”)。
机器人只能在任何时间点向下或向右移动。
有多少种可能的路径?
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 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
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
Input: m = 7, n = 3 Output: 28
思路:
从终点开始,依次往上/往左计算该格子到终点的路径数——因为每个格子只能走两个位置,即右和下,所以【每个位置到终点的路径数】 = 【其下格到终点路径数】 + 【其右格到终点路径数】
用一个与m×n相同大小的二维数组来存储每个位置到终点的路径数,最后返回matrix[0][0]的结果
初始化时,由于每个位置不能往上走,因此最下面一行都为1;又由于每个位置不能往左走,因此最右一列都为1,再依次往左上角计算,每次计算是按斜线的格子计算,如下图:
代码:
class Solution {
public int uniquePaths(int m, int n) {
int[][] path = new int[m][n];
for(int i=0;i<n;i++) {
path[m-1][i]=1;
}
for(int i=0;i<m;i++) {
path[i][n-1]=1;
}
update(path,m-2,n-2);
return path[0][0];
}
public void update(int[][] path,int m,int n) {
int count = m+n;
for(int i=count;i>=0;i--) {
for(int j=i;j>=0;j--) {
if(j<=m && i-j<=n) {
path[j][i-j] = path[j+1][i-j] + path[j][i-j+1];
}
}
}
}
}