题目:从左上角到右下角,只能往右走或者往下走,有多少种不同的走法。
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?
分析:动态规划,设f[i][j]表示从点(i,j)到终点有多少种不同的走法。那么f[i][j]=f[i+1][j]+f[i][j+1].
边界条件:f[m-1][n-1]=1
方向:从向往上,从右往左
复杂度:O(n²)。
用动态规划很慢呀,其实这道题可以直接计算。因为每种走法有m-1次向右,n-1次向下,所以其实就是从m+n-2次移动中选择m-1次为向右移,其他位向左移。
所以答案是C(m+n-2,m-1)。
代码(动态规划):
class Solution {
public:
int uniquePaths(int m, int n) {
if(m==0||n==0) return 0;
if(m==1||n==1) return 1;
vector<vector<int> > f(m,vector<int>(n, 0));
f[m-1][n-1]=1;
for(int j=n-1;j>=0;j--)
for(int i=m-1;i>=0;i--)
{
if(i+1<m) f[i][j]+=f[i+1][j];
if(j+1<n) f[i][j]+=f[i][j+1];
}
return f[0][0];
}
};
排列组合:
class Solution {
public:
int uniquePaths(int m, int n) {
double res=1;
int N=m+n-2;
int k=1;
while(k<=n-1)
{
res=res*(N-(n-1)+k)/k;
k++;
}
return (int)res;
}
};