【题目描述】
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是用深搜实现的,因为怕数字太大超时,所以还记录了前面的path数目。
代码2、3是用动态规划做的,状态方程是ans[i][j]=ans[i-1][j]+ans[i][j-1],代码2的space是O(m*n),后来看了discuss发现可以优化到O(N)(https://leetcode.com/discuss/38353/0ms-5-lines-dp-solution-in-c-with-explanations),
最后一个是用数学公式解决的,机器人走到终点一共要走m+n-2步,其中往右要走n-1步,所以问题变成了在m+ n - 2 个操作中,选择m–1 个时间点向下走,n-1个时间点向右走,选择方式有多少种。即 。
【代码】
1.
class Solution {
public:
vector<vector<int>> s;
int uniquePaths(int m, int n) {
this->s=vector<vector<int>> (m+1,vector<int>(n+1,0));
return dfs(m,n);
}
int dfs(int m,int n){
if(m<1||n<1) return 0;
if(m==1&&n==1) return 1;
return update(m-1,n)+update(m,n-1);
}
int update(int m,int n){
if(s[m][n]>0) return s[m][n];
else{
s[m][n]=dfs(m,n);
return s[m][n];
}
}
};
2.
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> ans(m,vector<int>(n,1));
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
ans[i][j]=ans[i-1][j]+ans[i][j-1];
}
}
return ans[m-1][n-1];
}
};
3.
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> ans(n,0);
ans[0]=1;
for(int i=0;i<m;i++){
for(int j=1;j<n;j++){
ans[j]+=ans[j-1];
}
}
return ans[n-1];
}
};
class Solution {
public:
int uniquePaths(int m, int n) {
return combination(m+n-2,max(m-1,n-1));
}
long long int combination(int a,int b){
long long int ret=1;
if(b==0) return 1;
if(b==1) return a;
ret=factor(b+1,a);
ret/=factor(1,a-b);
return ret;
}
long long int factor(int start,int end){
long long int ret=1;
for(int i=start;i<=end;i++){
ret*=i;
}
return ret;
}
};