LeetCode 62 Unique Paths 解題報告

Unique Paths
Total Accepted: 39541 Total Submissions: 120951
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.
這個題目可以不必使用動態規劃,而使用數學中的組合方法來得到答案。
對於一個mxn的棋盤,機器人需要往右移動n-1次,往下移動m-1次,
我們令p = m-1(往下移動p次);q=n-1(往右移動q次);
我們可以把問題轉換一下—用星號* 表示往右移動的事件,用|表示往下移動的事件。現在我們有p個|和q個*

*************

上面表示q個*
所有的路線情況可以想象爲將p個|插入到上面q個*的序列中的所有情況。
這個數字爲C(p,p+q) 用組合數學裏面的隔板法可以得出這個結論。
所以這個題就轉化爲了計算c(p,p+q)也就是c(m-1,m+n-2)的值

class Solution {
public:
    int uniquePaths(int m, int n) {
        --m;
        --n;
        if(m > n)
            swap(m, n);
        double result = 1;
        for(int i = 0; i < m; ++i)
        {
            result = result * (m + n - i) / (i + 1);
        }
        return static_cast<int>(result);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章