C#LeetCode刷题之#62-不同路径(Unique Paths)

问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3680 访问。

一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。

机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。

问总共有多少条不同的路径?

在这里插入图片描述

例如,上图是一个7 x 3 的网格。有多少可能的路径?

说明:m 和 n 的值均不超过 100。

输入: m = 3, n = 2

输出: 3

解释:

从左上角开始,总共有 3 条路径可以到达右下角。

  1. 向右 -> 向右 -> 向下
  2. 向右 -> 向下 -> 向右
  3. 向下 -> 向右 -> 向右

输入: m = 7, n = 3

输出: 28


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.

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

Input: m = 7, n = 3

Output: 28

示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3680 访问。

public class Program {

    public static void Main(string[] args) {
        var m = 7;
        var n = 3;

        var res = UniquePaths(m, n);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static int UniquePaths(int m, int n) {
        if(m == 0 || n == 0) return 0;
        var dp = new int[m, n];
        for(var i = 0; i < m; i++) {
            for(var j = 0; j < n; j++) {
                dp[i, j] = 1;
            }
        }
        for(var i = 1; i < m; i++) {
            for(var j = 1; j < n; j++) {
                dp[i, j] = dp[i, j - 1] + dp[i - 1, j];
            }
        }
        return dp[m - 1, n - 1];
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3680 访问。

28

分析

显而易见, 以上算法的时间复杂度为: O ( m n ) O(m*n)

猜你喜欢

转载自blog.csdn.net/qq_31116753/article/details/84307624