> 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.問題

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

![](/files/-LN9_ZHFC1PS_CG2_Jok)

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