# \[62]\[中等]\[动态规划] 不同路径

## 题目描述

[62. 不同路径](https://leetcode-cn.com/problems/unique-paths/)

一个机器人位于一个 m x n 网格的左上角 （起始点在下图中标记为“Start” ）。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角（在下图中标记为“Finish”）。

问总共有多少条不同的路径？

![](/files/-MI7NvNKuIiaukKrqfz0)

例如，上图是一个7 x 3 的网格。有多少可能的路径？

示例 1:

```
输入: m = 3, n = 2
输出: 3
解释:
从左上角开始，总共有 3 条路径可以到达右下角。
1. 向右 -> 向右 -> 向下
2. 向右 -> 向下 -> 向右
3. 向下 -> 向右 -> 向右
```

示例 2:

```
输入: m = 7, n = 3
输出: 28
```

提示：

* 1 <= m, n <= 100
* 题目数据保证答案小于等于 2 \* 10 ^ 9

## 解题思路

### 动态规划

```python
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [[1] * n for _ in range(m)]

        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        return dp[-1][-1]
```

### 滚动数组

可以看到状态转移公式只是用`dp[i - 1][j]`和`dp[i][j - 1]`的值, 因此用一列的长度, 配合从上到下循环(或一行的长度, 从左到右循环)就足够了. 对应的空间复杂度为$$O(\min({m,n}))$$

```python
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        if m > n:
            m, n = n, m
        dp = [1] * m

        for _ in range(1, n):
            for i in range(1, m):
                dp[i] = dp[i] + dp[i - 1]
        return dp[-1]
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kerasnoone.gitbook.io/garnet/suan-fa/dong-tai-gui-hua/62-bu-tong-lu-jing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
