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.
判断机器人有几种路线到达终点。在只能往下往右走的情况下。
思路:有个规律,map[i][j] = map[i-1][j]+map[i][j-1]
每一格的路线数等于他上面和左边格子的路线和。所以通过设置第一行第一列为一,之后遍历即可得到最后一个格子,就是终点的路线数。
public class Solution {
public int UniquePaths(int m, int n) {
int[][] map = new int[m][];
for(int i = 0; i<m;i++){
map[i] = new int[n];
map[i][0] = 1;
}
for(int j= 0;j<n;j++){
map[0][j]=1;
}
for(int i = 1;i<m;i++){
for(int j = 1;j<n;j++){
map[i][j] = map[i-1][j]+map[i][j-1];
}
}
return map[m-1][n-1];
}
}