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?
最基础的动态规划,但是可以用组合数学的思想解决:
public class Solution {
// 假如是一个5*5的矩阵
// 1,1,1,1,1
// 1,2,3,4,5
// 1,3,6,10,15
// 1,4,10,20,35
// 1,5,15,35,70
// 这样发现特别像杨辉三角(本人数学太差-也不懂其中的奥秘)
// 总之,我们还可以以另外一种方式计算,那就是数学方法:
// 相当于从最左端到最右下角-我们需要向右走(n-1)步向下走(m-1)步
// 那么,我们只需要在(m+n-2)步中选出向右走的或者向下走的步数就可以了:
// 因此很简单的数学公式了!
// 但是最简单的数学公式如果暴力求解不是很乐观,因此还是结合最开始的动态规划,这种动态规划实际上就是一种组合数
//C(m+n-2,m-1)
public int uniquePaths(int m, int n) {
return CMN(m+n-2,n-1);
}
public int CMN(int m,int n){
n=Math.min(m-n, n);//zhe这句一定要有 目的是让long不越界
long re=1;
for(int i=m,j=1;j<=n;i--,j++){
re*=i;
re/=j;
}
return (int)re;
}
//这个代码是不可以的 无论令re为double型还是long型 (long型可能造成数组越界 double型会导致精确度不够 结果和理论结果差1)
// public int CMN(int m,int n){
// long re=1;
// for(int i=m,j=1;j<=n;i--,j++){
// re*=i;
// re/=j;
// }
// return (int)re;
// }
}
注意:如果用long型存储结果依然会越界 而用double会因为精度问题造成结果错误,所以这一步至关重要:
n=Math.min(m-n, n);