LeetCode Unique Paths(062)解法總結

NewCoder1024發表於2020-03-08

描述

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?

LeetCode Unique Paths(062)解法總結

Above is a 7 x 3 grid. How many possible unique paths are there?

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right複製程式碼

Example 2:

Input: m = 7, n = 3
Output: 28複製程式碼

Constraints:

1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.複製程式碼

思路

知乎上學到了動態規劃的基本知識,就找了這道題作為練習鞏固。

此題以棋盤為dp陣列的形象描述,有助於初學者進行理解。

  • 除第一行及第一列的格子只有一種到達方式外,其他的格子需要從左邊/上邊的格子讀取上一個狀態,並將這兩個狀態相加,得到最右下角的路徑數。

關係式是 dp[i][j] = dp[i-1][j] + dp[i][j-1]

class Solution {
    public int uniquePaths(int m, int n) {
        int dp[][] = new int[m][n];
        for(int i = 0; i<n; i++){
            dp[0][i] = 1;
        }
        for(int i = 0; i<m; i++){
            dp[i][0] = 1;
        }
        for(int i = 1; i<m; i++){
            for(int j = 1; j<n; j++){
                dp[i][j] = dp[i-1][j] + dp[i][j-1];
            }
        }
        return dp[m-1][n-1];
    }
}複製程式碼
Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Paths.
Memory Usage: 36.6 MB, less than 5.10% of Java online submissions for Unique Paths.

優化

可以看到空間利用率還是比較低的,可以對其進行優化

參照原作者給出的思路(圖源見水印,下同):

這是矩陣初始化的時候(下圖)

LeetCode Unique Paths(062)解法總結

根據上一行的數值及第一列的數值(恆為1)計算第二行(下圖)

LeetCode Unique Paths(062)解法總結

計算過程(下圖*3)

LeetCode Unique Paths(062)解法總結

LeetCode Unique Paths(062)解法總結

LeetCode Unique Paths(062)解法總結

可以觀察到,第i行j列的資料生成之後,第i-1行j列的資料就可以不用儲存了。即滿足關係式dp[i] = dp[i-1] + dp[i]。照此推理過程不難推出最後一行的情況(下圖)

LeetCode Unique Paths(062)解法總結

右下角即為所求。

class Solution {
    public int uniquePaths(int m, int n) {
        int dp[] = new int[n];
        for(int i = 0; i<m; i++){
            dp[0] = 1;
            for(int j = 1; j<n; j++){
                dp[j] = dp[j-1] + dp[j];
            }
        }
        return dp[n-1];
    }
}複製程式碼
Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Paths.
Memory Usage: 36.5 MB, less than 5.10% of Java online submissions for Unique Paths.

數學優化(來自LeetCode題目評論區)

The total number of movements of the robot is S=m+n-2, and the number of downward movements is D=m-1. Then the problem can be seen as the number of combinations of D positions taken from S. The solution to this problem is C(S, D).

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        return math.factorial(m+n-2)/math.factorial(m-1)/math.factorial(n-1)複製程式碼

使用數學組合方法進行計算,空間複雜度O(1)

相關文章