62 Unique Paths 不同路徑
Description:
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Example:
Example 1:
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:
- Right -> Right -> Down
- Right -> Down -> Right
- Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
Constraints:
1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
題目描述:
一個機器人位于一個 m x n 網(wǎng)格的左上角 (起始點在下圖中標(biāo)記為“Start” )寸莫。
機器人每次只能向下或者向右移動一步醒第。機器人試圖達到網(wǎng)格的右下角(在下圖中標(biāo)記為“Finish”)。
問總共有多少條不同的路徑猖辫?
示例 :
示例 1:
輸入: m = 3, n = 2
輸出: 3
解釋:
從左上角開始窄俏,總共有 3 條路徑可以到達右下角。
- 向右 -> 向右 -> 向下
- 向右 -> 向下 -> 向右
- 向下 -> 向右 -> 向右
示例 2:
輸入: m = 7, n = 3
輸出: 28
提示:
1 <= m, n <= 100
題目數(shù)據(jù)保證答案小于等于 2 * 10 ^ 9
思路:
- 數(shù)學(xué)法
本質(zhì)上是從 m + n - 2步中選出 m - 1(n - 1)步
時間復(fù)雜度O(1), 空間復(fù)雜度O(1) - 動態(tài)規(guī)劃
每一格的步數(shù)等于左邊加上邊的步數(shù)
時間復(fù)雜度O(mn), 空間復(fù)雜度O(mn)
代碼:
C++:
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.back().back();
}
};
Java:
class Solution {
public int uniquePaths(int m, int n) {
int dp[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0) dp[i][j] = 1;
else dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
}
Python:
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return math.factorial(m + n - 2) // (math.factorial(m - 1) * math.factorial( n - 1))