题目:
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:我的解法采用的是高中所学的排列与组合。m*n格中移动的步数总和为m+n-2,题目的答案即为在m+n-2步中,向下的步m-1步的取法,C(m-1,m+n-2)。代码如下:
public:
int uniquePaths(int m, int n) {
allstep=m+n-2;
minnum = min(m-1,n-1);//取m-1,和n-1中的较小者,简化运算。
if(1 == m || 1 == n)
{
return 1;
}
else{
for ( int i = 0; i < minnum; i++)
{
Upresult *= allstep - i;//计算m-1,或者n-1,插入到allstep中的不同排列。
Downresult *= i + 1;//计算m-1,或者n-1,的全排列。
}
return result = Upresult / Downresult;//结果
}
}
private:
int allstep=0;
int minnum=0;
/*
*关键地方,想到排列组合的人不在少数,但是能考虑连乘结果会超过"int"取值范围的人应该不多。
*笔者提交返回结果为(m,n)=(10,10)出错,考虑了很久,最后到编译器里才发现Upresult超过了"int"的取值范围,因此采用long long型。
*/
long long Upresult=1;
long long Downresult=1;
int result=0;
};