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. “数值分析”类算法

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