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.
方法数就是求组合数,在(m-n-2)步中找出(m-1)步竖着走就可以了。写计算组合数写了好久,要用long来存储才不会溢出,同时注意从后面往前乘就不会出现精度问题。
public int uniquePaths(int m, int n) {
if(m == 1 || n == 1) return 1;
long i = n, j = 1, res = 1;
while(j <= m-1) {
res = res * i / j;
i++; j++;
}
return (int)res;
}
没有评论:
发表评论