LeetCode 62. Unique Paths (独立路径)

原题

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

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.

Example 1:

IInput: 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

Reference Answer

思路分析

这道题和climbing stairs很像,可以用动态规划解决。状态转移方程为dp[i][j]=dp[i-1][j]+dp[i][j-1]。

class Solution:
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """

        if m ==1 and n == 1:
            res = [[1]]
        elif m == 1 and n > 1:
            res = [[1 for i in range(n)]]
        elif n == 1 and m > 1:
            # res = [[1 for i in range(m)]]
            res = [[1] for i in range(m)]
        else:
            res = [[0 for i in range(n)] for i in range(m)]
            for i in range(m):
                res[i][0] = 1
            for i in range(n):
                res[0][i] = 1
            for i in range(1, m):
                for j in range(1, n):
                    res[i][j] = res[i][j-1] + res[i-1][j]
        return res[m-1][n-1]

        

反思:

  1. 这道题卡了很长时间,其中一个错误就是:
    	elif n == 1 and m > 1:
                # res = [[1 for i in range(m)]]
                res = [[1] for i in range(m)]
    
    中把矩阵行赋值当成了与矩阵列赋值一样的操作,尤其注意行赋值方式res = [[1] for i in range(m)]
  2. 这种通过设定矩阵为1,然后采用动态规划dp[i][j]=dp[i-1][j]+dp[i][j-1]进行求解的方式很清奇。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84566351