題目英文
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?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
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:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
題目中文
一個機器人位於一個 m x n 網格的左上角 (起始點在下圖中標記爲“Start” )。
機器人每次只能向下或者向右移動一步。機器人試圖達到網格的右下角(在下圖中標記爲“Finish”)。
問總共有多少條不同的路徑?
例如,上圖是一個7 x 3 的網格。有多少可能的路徑?
說明:m 和 n 的值均不超過 100。
示例 1:
輸入: m = 3, n = 2
輸出: 3
解釋:
從左上角開始,總共有 3 條路徑可以到達右下角。
1. 向右 -> 向右 -> 向下
2. 向右 -> 向下 -> 向右
3. 向下 -> 向右 -> 向右
示例 2:
輸入: m = 7, n = 3
輸出: 28
示例 3:
輸入: m = 23, n = 12
輸出: 193536720
算法實現
方式一:利用遞歸
public class Solution
{
private int _m;
private int _n;
public int UniquePaths(int m, int n)
{
_m = m;
_n = n;
int count = 0;
RecordPaths(0, 0, ref count);
return count;
}
private void RecordPaths(int i, int j, ref int count)
{
if (i == _m - 1 && j == _n - 1)
{
count++;
return;
}
if (i < _m)
{
RecordPaths(i + 1, j, ref count);
}
if (j < _n)
{
RecordPaths(i, j + 1, ref count);
}
}
}
使用遞歸的方式,容易理解但會耗費大量的時間,所以在運行 示例3 的時候,超時了。
方式二:利用動態規劃
動態規劃表格01:
動態規劃表格02:
動態規劃的最優子結構爲:d[i,j] = d[i-1,j] + d[i,j-1]
public class Solution
{
public int UniquePaths(int m, int n)
{
int[,] memo = new int[m, n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (i == 0)
{
memo[i, j] = 1;
}
else if (j == 0)
{
memo[i, j] = 1;
}
else
{
memo[i, j] = memo[i - 1, j] + memo[i, j - 1];
}
}
}
return memo[m - 1, n - 1];
}
}
實驗結果
- 狀態:通過
- 62 / 62 個通過測試用例
- 執行用時: 52 ms, 在所有 C# 提交中擊敗了 93.18% 的用戶
- 內存消耗: 13.6 MB, 在所有 C# 提交中擊敗了 17.65% 的用戶
相關圖文
1. “數組”類算法
- LeetCode實戰:三數之和
- LeetCode實戰:最接近的三數之和
- LeetCode實戰:求衆數
- LeetCode實戰:缺失的第一個正數
- LeetCode實戰:快樂數
- LeetCode實戰:尋找兩個有序數組的中位數
- LeetCode實戰:盛最多水的容器
- LeetCode實戰:刪除排序數組中的重複項
- LeetCode實戰:搜索旋轉排序數組
- LeetCode實戰:螺旋矩陣
2. “鏈表”類算法
- LeetCode實戰:兩數相加
- LeetCode實戰:刪除鏈表的倒數第N個節點
- LeetCode實戰:合併兩個有序鏈表
- LeetCode實戰:合併K個排序鏈表
- LeetCode實戰:兩兩交換鏈表中的節點
- LeetCode實戰:旋轉鏈表
- LeetCode實戰:環形鏈表
3. “棧”類算法
4. “隊列”類算法
5. “遞歸”類算法
6. “字符串”類算法
7. “樹”類算法
8. “哈希”類算法
9. “搜索”類算法
10. “動態規劃”類算法
11. “回溯”類算法
11. “數值分析”類算法