LeetCode C++ 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?

在這裏插入圖片描述
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.

題意:機器人從左上角走到右下角,每次只能夠向右或下移動一格,求最終有多少種走法。

思路1:排列組合。無論如何都要走 m + n - 2 步,每一條路線必然有 m - 1 步走豎向,n - 1 步走橫向。因此,有 Cm+n2m1C^{m-1}_{m+n-2} 種走法。

不過計算組合數/排列數有點煩,很容易溢出。這裏不這樣寫。

思路2:動態規劃。這個題很容易得到狀態轉移方程,dp[i][j] = dp[i - 1][j] + dp[i][j - 1] ,其中 dp[i][j] 是走到 i,j 位置的走法總數。dp[1][1] = 1 爲左上角。

代碼:

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