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];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章