> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/62.-unique-paths.md).

# 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];
    }
};
```
