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.
此题思路有3种!
1、直接数学公式,用组合的方法,直接用(M+N-2)!/(M-1)!*(N-1)! 意思是 水平方向有 n-1 中选择,垂直方向 m-1中选择。所以总体有 m+n-2,只需在这m+n-2种方式选择向右走 n-1 步或者 向下的m-1 步即可。注意实现 (n-m)!的函数即可,注意溢出问题!
2、利用DFS,每个地方都有俩种可能,依次即可,记得带备忘录(缓存数据)-提高速度。
3、可知此题涉及子问题重叠,故而会想到DP算法,以下是实现。
dp[i][j] 表示从[0][0]到[i][j] 的所有路径之和。有以下转移方程:dp[i][j] = dp[i-1][j] + dp[i][j-1];
处理上述时,注意到 i = 0,j = 0需特殊处理!
int uniquePaths(int m, int n)
{
return count_paths(m,n);
}
int count_paths(int m,int n)
{
vector<vector<int>> dp(m,vector<int>(n,0));//dp[][]
dp[0][0] = 1;
for (int i = 1;i < n;i++)
{
dp[0][i] = 1;
}
for (int i = 1;i < m;i++)
{
dp[i][0] = 1;
}
for (int i = 1;i < m;i ++)
{
for (int j = 1;j < n;j++)
{
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}