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];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章