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.
Show Tags
SOLUTION 1:
使用DP解决之。很简单。某一个cell有2种可能到达,从上面来,以及从左边来,只需要把每一个cell的可能数计算好,并且把它们相加即可。
另外,在第一行,第一列,以及左上角需要特别处理,因为我们上面、左边并没有cells.
public class Solution {
public int uniquePaths(int m, int n) {
if (m <= || n <= ) {
return ;
} int[][] D = new int[m][n]; for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (i == && j == ) {
D[i][j] = ;
} else if (i == ) {
D[i][j] = D[i][j - ];
} else if (j == ) {
D[i][j] = D[i - ][j];
} else {
D[i][j] = D[i - ][j] + D[i][j - ];
}
}
} return D[m - ][n - ];
}
}