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?
解题思路一:
很明显,答案是C(m+n-2,n-1),是一个排列组合问题,直接使用int进行操作的话,会发生数据溢出,不过好在我们有BigInteger,JAVA实现如下:
import java.math.BigInteger; public class Solution { public int uniquePaths(int m, int n) { return Cmn(m,n).intValue(); } static BigInteger Cmn(int m, int n){ return Amn(m + n - 2, n - 1).divide(factorial(n - 1)); } static BigInteger Amn(int m, int n) { if (n == 0) return BigInteger.valueOf(1); if (n == 1) return BigInteger.valueOf(m); else return Amn(m - 1, n - 1).multiply(BigInteger.valueOf(m)); } static BigInteger factorial(int n) { if (n == 1 || n == 0) return BigInteger.valueOf(1); else return factorial(n - 1).multiply(BigInteger.valueOf(n)); } }
解题思路二:
很明显uniquePaths(int m, int n)=uniquePaths(int m-1, int n)+uniquePaths(int m, int n-1),结果提交发现Time Limit Exceeded,看来不能直接用递归计算。不过基于上述结论,我们可以采用dp的方法,开一个数组v[j]表示经过i步右移和j步下移后达到(i,j)的路径数目,前进方法为v[j] += v[j - 1],表示v[j]由从左边过来的v[j-1]和从上面下来的前一个v[j]组成,JAVA实现如下:
static public int uniquePaths(int m, int n) { int[] v = new int[n]; for (int i = 0; i < v.length; i++) v[i] = 1; for (int i = 1; i < m; ++i) for (int j = 1; j < n; j++) v[j] += v[j - 1]; return v[n - 1]; }