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?
Example 2:
Input: m = 7, n = 3
Output: 28
这道题求矩阵左上角到右下角的路径数,要求只能往右或者往下走。之前接触动态规划比较少,感觉无从下手,参考答案后知道,可以基于动态规划的方式来求解。
解法一:动态规划
int uniquePaths(int m, int n) {
//到达第0行第j列的路径数只有1条
vector<int> dp(n, 1);
//这里直接忽略了第0行和第0列,原因是到达第0行和第0列的某个位置的路径都只有1条
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
//dp[j]表示从左上角到达第i行和第j列的不同路径数
//对于点(i,j),只能从上面的点(i-1,j)和左面的点(i,j-1)到达
dp[j] = dp[j]+dp[j - 1];
}
}
return dp[n - 1];
}
解法二:排列组合
一共需要(m-1)+(n-1)步,只能往右走或者往下走,所以实质就是从m+n-2中取出m-1个步数往下走,或者是取出n-1个步数往右走,排列组合。
int uniquePaths(int m,int n){
long x=m+n-2;//阶乘大,可能溢出,使用long
long y=min(m,n)-1;
int up=1,down=1;//分子,分母
for(int i=0;i<y;i++){
up*=x--;
}
for(int i=y;i>0;i--){
down*=y;
}
return int(up/down);
}
python写法:
def uniquePaths(self,m,n):
if not m or not n:
return 0
dp=[[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
if i==0 or j==0:
dp[i][j]=1
else:
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[-1][-1]