mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
23 lines
877 B
Markdown
23 lines
877 B
Markdown
![]() |
# [62. Unique Paths](https://leetcode.com/problems/unique-paths/)
|
|||
|
# 思路
|
|||
|
题目要求从网格矩形的左上角移动到右下角共有多少可能的路径,一次移动只能向右或向下。
|
|||
|
就是一个简单的递归,设置一个大小为(m + 1)x(n + 1)的数组dp(初始值全为0), dp[i][j]代表从左上角到达位置第i行第j列的路径数,
|
|||
|
则根据题意可知`dp[1][1] = 1`、`dp[i][j] += (dp[i - 1][j] + dp[i][j - 1])`。最终的返回结果就是dp[m][n]。
|
|||
|
时间复杂度O(mn),空间复杂度O(mn)
|
|||
|
|
|||
|
# C++
|
|||
|
``` C++
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
int uniquePaths(int m, int n) {
|
|||
|
vector<vector<int>>dp(m + 1, vector<int>(n + 1, 0));
|
|||
|
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];
|
|||
|
}
|
|||
|
};
|
|||
|
```
|