LeetCode實戰:不同路徑

題目英文

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:

表01

動態規劃表格02:

表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. “數組”類算法

2. “鏈表”類算法

3. “棧”類算法

4. “隊列”類算法

5. “遞歸”類算法

6. “字符串”類算法

7. “樹”類算法

8. “哈希”類算法

9. “搜索”類算法

10. “動態規劃”類算法

11. “回溯”類算法

11. “數值分析”類算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章