LeetCode 62 _ Unique Paths 全部不同路径
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; }
一个很有趣的一点是,求组合数时,将分子上按大数排列,分母按小数排列,可以避免产生循环小数的情况,例如:
C8(2) = 8*7*6/(1*2*3) = 56
= 8*7*6/(3*2*1) = 55
这是由于double转int时将循环小数部分直接删除导致的差异
提交情况:
public int uniquePaths(int m, int n) { return temp(m-1, n-1); } int temp(int a, int b){ if (a == 0 || b == 0){ return 1; } return temp(a, b-1) + temp(a-1,b); }