Unique Paths

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 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.



是一个排列组合的问题,对于一个m*n的grid来说, 解的数目应该是 C m-1/m+n-2

关键就在于怎么算这个解, 如果正常按照公式来算, 那么当m或者n比较大的时候阶乘的数目有可能会大于integer的最大值,于是这里用到组合算法的一个性质:


C k/m = C k-1/m-1 + C k/m-1


在这道题里面的物理意义是, 走到下标为 i,j的方法数目,相当于先走到下表为i-1,j的方格再往下走一步或者是先走到i,j-1的方格然后再往右走一步。所以解题代码如下


public class Solution {
    public int uniquePaths(int m, int n) {
        if(m==1||n==1){
            return 1;
        }
        int [][]r = new int[m][n];
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(i==0||j==0){
                    r[i][j] = 1;
                }else{
                    r[i][j] = r[i-1][j]+r[i][j-1];  
                }
            }
        }
        return r[m-1][n-1];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章