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?
class Solution {
public:
int uniquePaths(int m, int n) {
if(m<0||n<0)
return 0;
int sum=m+n-2;
long long mul=1;
for(int i=sum;i>=m;i--){
mul*=i;
}
for(int i=1;i<=n-1;i++){
mul/=i;
}
return mul;
}
};
上面这个解法是最简单的 ,但是却会造成越界怎么办呢
还是得用老方法
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> v(n,1);
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
v[j]=v[j]+v[j-1];
}
}
return v[n-1];
}
};
这个方法是下面的方法的变种
当然由于以下的方法是每次只需要“1”的空间,而且按层进行遍历。故而可以简化
v[i][j]=v[i-1][j]+v[i][j-1];