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.
题意:算机器人从(1,1)走到(3,7)这个坐标的可能路线数,这里为方便假设以向下和下右为正方向,坐标以 (行,列) 的形式
注意机器人其实是进行了m-1次下移和n-1次的右移,还有m和n至多为100
思路:这道题如果联系上组合数学里的格路模型会非常简单
可以这样想,机器人一共走了 m+n-2步,其中有m-1步下移和n-1步右移,所以总的路线数就是组合数C(m+n-2, n-1)或者C(m+n-2, m-1)
这里再说一种个人觉得更加好理解的解释
假设向下走记为"D",向右走记为"R",那么这道题相当于算m-1个D和n-1个R的排列数
但要注意的是这里D和R是个可重排列的问题,所以要除以两个数的重复度
所以结果是result = P(m+n-2, m+n-2) / (m-1)! / (n-1)!
有了数学理论的指导代码就很简单了,这里需要注意的是问题规模组合数C(198, 99)不会超过int型的范围,但计算过程中间结果可能会溢出,可以先用double暂存最后再转成int
public int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
if (m == 1 || n == 1) {
return 1;
}
m--;
n--;
return combination(m+n, n);
}
//算组合数的函数C(m, n)
int combination(int m, int n) {
if (n == 0 || m == 0 || n == m) {
return 1;
}
double result = 1;
for (int i=m; i>=m-n+1; i--) {
result *= i;
result /= m-i+1;
}
return (int) Math.ceil(result);
}