LeetCode第[62]題(Java):Unique Paths 及擴充

來源:互聯網
上載者:User

標籤:符號   sed   資料   斐波那契   not   exec   []   The   結果   

題目:唯一路徑(機器人走方格)

難度:Medium

題目內容:

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網格的左上方(在中標記為“開始”)。

機器人只能在任何時間點移動或向右移動。機器人正試圖到達網格的右下角(在中標記為“Finish”)。

有多少種可能的路徑?

 

Note: m and n will be at most 100.

Example 1:

Input: m = 3, n = 2Output: 3

Example 2:

Input: m = 7, n = 3Output: 28

 

我的思路:動態規劃題,每個點(m,n)都是由(m-1,n)+(m,n-1)這兩個點的可能數之和。最簡單的方法就是用遞迴來實現。

 

My Code:

1     public int uniquePaths(int m, int n) {2         if (m == 1 || n==1) {3             return 1;4         }5         return uniquePaths(m,n-1) + uniquePaths(m-1,n);6     }

我的複雜度:O(m*n)    空間複雜度也是O(m*n) ——遞迴深度

結果:41 / 62 test cases passed.     Time Limit Exceeded

Last executed input:   51  9

遞迴就是這樣,代碼很簡單,但是運行速度很慢,稍微大一點就會逾時。

 

答案代碼:

 1     public int uniquePaths(int x, int y) { 2         int dp[][] = new int[x][y]; 3         for(int i = 0; i< x;i++){ 4             for(int j = 0;j<y;j++){ 5                 if (i == 0 || j == 0) { 6                     dp[i][j] = 1; 7                     continue; 8                 } 9                 dp[i][j] = dp[i-1][j] + dp[i][j-1];10             }11         }12         return dp[x-1][y-1];13     }

答案複雜度:O(m*n)    空間複雜度也是O(m*n)  雖然複雜度都一樣,但是由於用迭代替換了遞迴,運行速度大大提高。

答案思路:遞迴無非就是把本層的計算調用深一層的計算,然後將深一層的結果返回,所以如果將從第一層到最後一層所有的值都計算出來並由某種資料結構儲存,那麼就可以直接迭代進行計算。

所以一維的遞迴:一維只會與一維相關,所以一路直線迭代即可。例如:求階乘(只與上一個有關,記錄一個即可)、斐波那契數列(與上兩個有關,需要記錄兩個)

  二維的遞迴:每一個元素都與兩個維度相關,所以得借用二維數組來記錄所有值。

 

擴充:當x == y的時候,此時為正方格,是否有更好的方法?

  因為此時類似於卡特蘭數,此時有 f(n+1)=f(n)* (4*n-2),所以代碼中加入方形判斷可以最佳化方形的計算速度,如下:

        if (x == y) {            int ans = 1;            for (int i = 1; i < x; i++) {                ans = ans * (4*i-2)/i;            }            return ans;        } 

注意:當要使用  “  *=  ”  這種符號的時候,如果右邊是一個運算式且含有 除號 ,那麼最好還是不要使用,因為這個運算子是先運算右邊再乘自己,所以有可能右邊的計算順序就不對了。

例如當x==y==4的時候  此時ans = =6   而  i ==3 ,如果使用  ans *= (4*i -2)/i; 所以先計算右邊就有   10 /  3 = 3,  然後再乘以6  最後結果為18,結果錯誤。

而使用 ans = ans * (4*i-2)/i; 就不會有此錯誤。

 

LeetCode第[62]題(Java):Unique Paths 及擴充

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.