
目录
问题
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
问总共有多少条不同的路径?

例如,上图是一个7 x 3 的网格。有多少可能的路径?
说明:m 和 n 的值均不超过 100。
输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 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:
- Right -> Right -> Down
- Right -> Down -> Right
- Down -> Right -> Right
Input: m = 7, n = 3
Output: 28
示例
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种算法实现,以下是这个案例的输出结果:
28
分析
显而易见, 以上算法的时间复杂度为:O(m*n)O(m∗n) 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3680。