Description:
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
Solution:
这道题让我们求出从规格为m*n的方格左上角走到右下角的所有不同路径总数
这道题很简单,我们知道,如果不走回头路,那么机器人只能向右或向下走,7*3的方格实际上要向右走6次,向下走2次
所以该问题本质是“m个A,n个B,有多少种不同排列”的高中概率论问题
求法即为在(m+n)个空位中选择m个空位给A,剩下的即为B的位置
答案即C62,通用解为(m+n)!/(m!*n!)
由于中间可能在乘分子的时候超过范围,因此中间值sum最好取double,以使结果的范围更大
Code:
public int uniquePaths(int m, int n) { if (m <= 0 && n <= 0){ return 0; } int total = m + n - 2; int less = Math.min(m,n) - 1; double sum = 1; for (int i = 1; i <= less; i++){ sum = sum * (total + 1 - i) / i; } return (int)sum; }
提交情况:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Paths.
Memory Usage: 31.8 MB, less than 100.00% of Java online submissions for Unique Paths.
原文地址:https://www.cnblogs.com/zingg7/p/10655801.html