题目
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.
解析
我一看到这个题目,脑海里冒出来的就是数学思维。例如7x3的格子,你需要走的步数一共是(7-1)+(3-1) = 8,理由是因为走的时候是从一个格子走到另一个格子算作一步。
一共走这么多步,但是有(7-1)步是横着走的。其实我们只需要从这8步中选出哪6步是横着走的就可以了,也就是数学公式排列组合的C{6,8}
总结一下
假设是m x n的矩形,我们不妨默认m<=n
则步数一共是
因此只要实现阶乘的运算就可以了,不过麻烦的是阶乘的运算会溢出,我的办法是用double型来计算,最后accept了。
class Solution {
public:
double CountPai(double a,double b)
{
double sum = 1;
while (a != b)
{
sum = a * sum;
a ++;
}
return sum*a;
}
int uniquePaths(int m, int n) {
m--;n--;
if(m*n==0)
return 1;
if (m>=n)
{
double a = CountPai(m+1,m+n);
double b = CountPai(1,n);
return (int)(a/b);
}
else
{
double a = CountPai(n+1,m+n);
double b = CountPai(1,m);
return (int)(a/b);
}
}
};
这是一种纯数学的方法。
其实用动态规划的思路就很简单了,理论上建立一个二维数组path[i][j],表示到i,j位置的元素的路径有多少个。
则显然path[0][j]都是1,path[i][0]也都是1,
path[i][j] = path[i-1][j] + path[i][j-1]
再节省空间一下,其实一维数组就足够了,从第一行开始扫描,后面的去累加就行
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> path(n,1);
for (int i = 1;i<m;i++)
{
for (int j = 1;j<n ;j++)
{
path[j] += path[j-1];
}
}
return path[n-1];
}
};