62. Unique Paths -Medium

Question

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?

Note: m and n will be at most 100.

62. Unique Paths -Medium_第1张图片

一个机器人位于m x n的表格的左上角,它只会向右走或向下走。这个机器人想要走到表格的右下角,有几种方法。(m,n最多100)

Example

None

Solution

  • 动态规划解。定义dp[i][j]:从左上角到grid[i][j]的方法数。递推式:dp[i][j] = dp[i - 1][j] + dp[i][j - 1]。即把来源的两个方向的方法数相加即可

    class Solution(object):
        def uniquePaths(self, m, n):
            """
            :type m: int
            :type n: int
            :rtype: int
            """
            if m == 0 or n == 0: return 0
            dp = [[0 for _ in range(n)] for _ in range(m)]
            for index_m in range(m):
                for index_n in range(n):
                    # 第一行和第一列均只有一个方向,所以方法数都为1
                    if index_m == 0 or index_n == 0:
                        dp[index_m][index_n] = 1
                    # 其余表格都有两个方向,相加即可
                    else:
                        dp[index_m][index_n] = dp[index_m - 1][index_n] + dp[index_m][index_n - 1]
            return dp[-1][-1]

你可能感兴趣的:(LeetCode-动态规划)