# 62. Unique Paths

## 1.問題

* 計算從起點到終點有多少可能的途徑

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LN82c4j1IbBfwOPhqN3%2F-LN9_ZHFC1PS_CG2_Jok%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-24%20%E4%B8%8B%E5%8D%883.58.04.png?alt=media\&token=e1b17a9b-58b7-4c33-97b5-c81e28a4bb57)

## 2.想法

* 提問
* function header, parameter
* test input
* 說明想法&#x20;
  * 動態規劃, 到每一點的途徑等於前一點(上面, 左邊)的總和, 方程式為dp\[i]\[j] = dp\[i - 1]\[j] + dp\[i]\[j - 1]
  * 特例: 因為機器人只能往下面跟往右邊, 因此對最上方的row來說, 不會有來自上方的機器人, 對最左邊的column來說, 不會有來自左邊的機器人
* 測試計算複雜度

## 3.程式碼

```
class Solution {
public:
    int uniquePaths(int m, int n) {
        if (m == 0 || n == 0) {
            return 0;
        }
        
        //每個值存放的是到這邊所可能的路徑數
        vector<vector<int>> dp(m, vector<int>(n, 0));
        dp[0][0] = 1;
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j > 0) {
                    //left
                    dp[i][j] = dp[i][j - 1]; 
                } else if (i > 0 && j == 0) {
                    //top
                    dp[i][j] = dp[i - 1][j];
                } else if (i > 0 && j > 0){
                   dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }
            }
        }
        
        return dp[m - 1][n - 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://jenhsuan.gitbook.io/algorithm/leetcode/62.-unique-paths.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.
