# LC 62. Unique Paths
### [Problem link](https://leetcode.com/problems/unique-paths/)
###### tags: `leedcode` `python` `c++` `medium` `DP` `Math`
There is a robot on an <code>m x n</code> grid. The robot is initially located at the **top-left corner** (i.e., <code>grid[0][0]</code>). The robot tries to move to the **bottom-right corner** (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.
Given the two integers <code>m</code> and <code>n</code>, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.
**Example 1:**
<img src="https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" style="width: 400px; height: 183px;" />
```
Input: m = 3, n = 7
Output: 28
```
**Example 2:**
```
Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
```
**Constraints:**
- <code>1 <= m, n <= 100</code>
## Solution 1 - DP
#### Python
```python=
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m == 1 or n == 1:
return 1
dp = [[1 for _ in range(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]
```
#### C++
```cpp=
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
for (int i = 0; i < n; i++) {
dp[0][i] = 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 - 1][n - 1];
}
};
```
#### C++
```cpp=
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>> dp(m, vector<int>(n, 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 - 1][n - 1];
}
};
```
## Solution 2 - DP
#### Python
```python=
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [1] * n
for i in range(1, m):
for j in range(1, n):
dp[j] += dp[j - 1]
return dp[-1]
```
#### C++
```cpp=
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> dp(n, 1);
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
};
```
## Solution 3 - Math
```python=
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return math.comb(m + n - 2, m - 1) # or math.comb(m + n - 2, n - 1)
```
>### Complexity
>| | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1 | O(mn) | O(mn) |
>| Solution 2 | O(mn) | O(n) |
>| Solution 3 | O(m + n - 2) | O(1) |
## Note
solution3:
res = ${m+n-2 \choose m-1}$ = ${m+n-2 \choose n-1}$ = ${{m+n-2} \over (m-1)!(n-1)!}$