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. 确定状态
    开数组的意义 dy[m-1][n-1]
    确定状态需要两个意识:
    • 最后一步
      dy[m-1][n-1] = dy[m-2][n-1] + dy[m-1][n-2]
    • 子问题
      从后往前推子问题,问题规模渐渐变小
  2. 转移方程
    dp[i][j] = dp[i-1][j] + dp[i][j-1]
  3. 初始条件和边界情况
    d[0][j] = 1
    d[i][0] = 1
  4. 计算顺序
    按行列的方向
class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        dp = [[0 for i in range(n)] for i in range(m)]
        for i in range(m):
            for j in range(n):
                if i == 0:
                    dp[i][j] = 1
                elif j == 0:
                    dp[i][j] = 1
                else:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]
        return dp[m-1][n-1]

请多多指教。

文章标题:62. Unique Paths

本文作者:顺强

发布时间:2020-04-16, 23:59:00

原始链接:http://shunqiang.ml/leetcode-62-unique-paths/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏