题目地址:Unique Paths
题目简介:
一个机器人位于一个网格的左上角(起始点在下图中标记为"start")。机器人每次只能向下或者向右移动一步,计算机器人从起点到终点可以有多少条不同的路径?
例如,上图是一个的网格,共有28条路径。说明,m和n的值均不超过100。
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
题目解析:
1、想当然的以为是个深搜,便开始递归,然后超时代码如下:
C++版:
class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 1 || n == 1)
return 1;
int ans = 0;
ans += m - 1 > 0 ? uniquePaths(m - 1, n) : 0;
ans += n - 1 > 0 ? uniquePaths(m, n - 1) : 0;
return ans;
}
};
2、因为只能继续往左或者往右行走,所以一个点的路径个数取决于它的右边到终点的路径条数和下边到终点的路径条数,只要将两条路径数加起来,便可以得到结果。
那么当起点和终点在一起时,路径只有一条。
C++版:
class Solution {
public:
int uniquePaths(int m, int n) {
int dp[m + 1][n + 1];
memset(dp, 0, sizeof(dp));
dp[1][1] = 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][n];
}
};
Python版:
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
print(dp)
dp[1][1] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] += (dp[i - 1][j] + dp[i][j - 1])
return dp[m][n]