Leetcode 62. 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?

分析

一個機器人在一個m X n的網格左上方,只能向下或者向右移動,有多少可能的路徑能夠到達最底下的網格。假如使用路徑搜索等遞歸算法,可能會超時。
我們可以在Excel中計算總路徑數,就會發現其中的規律。下面列出(m,n)的結果矩陣:

| n\m |1 | 2| 3|4|5|6|
| :-------- | --------:| :------: |:-------- | :-------- | :-------- |
| 1 |1 | 1 | 1| 1| 1| 1|
| 2 |1 | 2| 3|4|5|6|
| 3 | 1| 3| 6|10|15|21|
| 4 | 1| 4| 10|20|35|56|
| 5 | 1| 5| 15|35|70|126|
| 6 | 1| 6| 21|56|126 | 258|
可以看到這樣的規律(m,n)=(m-1,n)+(m,n-1),左邊的數字加上上邊的數字能夠得到該數字,也就是動態規劃的思想,要達到(m,n)的位置,只有兩個路徑(m,n-1)和(m-1,n),而這兩個之前計算過了,就不用計算了。因此可以列一個100X100的表,通過循環把所有的數都算出來,然后輸出結果即可。

其他人的方法:反正是向下和向右,不用管其順序,可以看做數學的組合問題,隨意組合,之后由于一直朝一個方向算一條獨特的路徑,因此再除去某數的階層!。

int uniquePaths(int m, int n) {
    int ans[101][101]={1};
    for(int i=1;i<101;i++)
        ans[1][i]=1;
    ans[2][1]=1;
    for(int i=2;i<101;i++)
    {
        ans[i][i]=2*ans[i-1][i];
        for(int j=i+1;j<101;j++)
        {
            ans[i][j]=ans[i][j-1]+ans[i-1][j];
        }
    }
    if(m>n)
        return ans[n][m];
    else
        return ans[m][n];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容