Leetcode每日一題(Unique Paths)

A robot is located at the top-left corner of amxngrid (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:mandnwill be at most 100.

題目如上,翻譯一下就是要找到所有的路徑,這種問題是一個比較簡單的問題,當然可以使用動態規劃,也就是記錄新矩陣的每個節點的數字等于到哪一個位置的路徑之和再往下走,所以最后一個點的數值就是到達該點的路徑和,也就是我們最終要求的數值。

假設原矩陣為m*n

那么新矩陣result:

result[0][0]=1;

result[0][j] = 1;

result[i][0] = 1;

result[i][j] = result[i][j-1]+result[i-1][j];

這樣就會發現:

假如是一個5*5的矩陣“

1 ? ? ? 1 ? ? ? 1 ? ? ? ?1 ? ? ? 1

1 ? ? ? 2 ? ? ? ?3 ? ? ? 4 ? ? ? ?5?

1 ? ? ? 3 ? ? ? ? 6 ? ? ? 10 ? ? ?15

1 ? ? ? 4 ? ? ? ? 10 ? ? ?20 ? ? ?35

1 ? ? ? 10 ? ? ? 20 ? ? ? 40 ? ? ?75


這樣發現特別像楊輝三角(本人數學太差-也不懂其中的奧秘)

總之,我們還可以以另外一種方式計算,那就是數學方法:

相當于從最左端到最右下角-我們需要向右走(n-1)步向下走(m-1)步

那么,我們只需要在(m+n-2)步中選出向右走的或者向下走的步數就可以了:

因此很簡單的數學公式了!

但是最簡單的數學公式如果暴力求解不是很樂觀,因此還是結合最開始的動態規劃,這種動態規劃實際上就是一種組合數


所以分析到現在發現竟然是一樣的:

實現方法:


這是最簡單的一種了,參考下面的鏈接可以得到計算組合數更好的方法了。


http://my.oschina.net/baoer1024/blog/62826

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容