题目描述
题目链接:62. Unique Paths
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?
例子
例子 1
Input:
m = 3, n = 7
Output:28
例子 2
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 -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
例子 3
Input:
m = 7, n = 3
Output:28
Constraints
1 <= m, n <= 100
- It’s guaranteed that the answer will be less than or equal to
2 * 10^9
.
解题思路
一般这种有多少种方法/路径的题目都可以考虑使用动态规划求解。具体做法为:
- 使用
mxn
的二维数组表示到每一格有几种走法(初始化为 0,左上角为 1)- 这里实现时可以使用
(m+1)x(n+1)
的二维数组用counts[i][j]
表示在(i,j)
(从 1 开始)的路径数
- 这里实现时可以使用
- 从左上角到右下角遍历,更新每一个格子:
counts[i][j] += (counts[i - 1][j] + counts[i][j - 1])
- 最后返回右下角元素即可
代码如下:
#include <vector>
class Solution {
public:
int uniquePaths(int m, int n) {
std::vector<std::vector<int>> counts(m + 1, std::vector<int>(n + 1, 0));
counts[1][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
counts[i][j] += (counts[i - 1][j] + counts[i][j - 1]);
}
}
return counts[m][n];
}
};
- 时间复杂度: O(mn)
- 空间复杂度: O(mn)
GitHub 代码同步地址: 62.UniquePaths.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions