题目描述:
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
分析:题目所求的路径可以转化为m个right和n个down的组合数用数学方法可求得。
代码如下:
int uniquePaths(int m, int n) {
double ans = 1;
if(m == 1 || n == 1)
return ans;
if(m<n){
swap(m,n);
}
m--;
n--;
int k = 1;
for(int i = m+1; i <= m+n; i++, k++){
ans *= i;
ans/= k;//结果为 (m+n)! / (m! * n!)
}
int temp=int(ans);
return temp;
}