[leetcode][python] 62. Unique Paths

62. Unique Paths


知识点:dynamic programming

1. 原题

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.

2. 题意

对于一个矩阵,从左上角走到右下角,在只能向右和向下的情况下,能有几种不同的路径可以走

3. 思路

对于产生一个二维矩阵的方法,不要用

list = [[0] * n] * m
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

因为这个是浅拷贝,一旦改变一行中的一个点,每一行中的对应那个点都会被改变

list[1][1] = 2
[[0, 2, 0], [0, 2, 0], [0, 2, 0]]

而是使用

list = [[0 for i in range(n)] for j in range(m)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

在改变之后,不会影响到其他点的数值

list[1][1] = 3
[[0, 0, 0], [0, 3, 0], [0, 0, 0]]

或者直接使用numpy

import numpy as np
# 创建一个 3x4 的数组且所有值全为 0
list = np.zeros((3, 4))
[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

我们要记得:让我们判断有多少种呢就是动态规划,一旦让我们写出全部的组合那就是回溯

3.1 使用递归来解决

对于到达一个点的所有可能路径就是这个点上面的点加左边的点的所有路径,使用递归获取来自这两种方向的可能路径数,直到递归到左或上的边界,当到达边界之后,就是只有一种可能路径,所以返回1。由于走路的方向只能向右或向下,所以来自左边和上边两个路径的集合之间没有交集,可以直接相加。

3.2 使用动态规划来解决

当在左或上边界时,是只有一种路径,而其他点的路径数就是来自左边和上边两个方向的路径之和。

4. 代码

4.1 使用递归来解决

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        ma=[[0 for i in range(n)] for j in range(m)]
        return self.dfs(m-1,n-1,ma)
        
    def dfs(self,m,n,ma):
        if n==0 or m==0:
            return 1
        if ma[m][n]:
            return ma[m][n]
        else:
            ma[m][n]=self.dfs(m-1,n,ma)+self.dfs(m,n-1,ma)
        return ma[m][n]

4.2 使用动态规划来解决

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        ma=[[0 for i in range(n)] for j in range(m)]
        for i in range(m):
            for j in range(n):
                if i==0 or j==0:
                    ma[i][j]=1
                else:
                    ma[i][j]=ma[i-1][j]+ma[i][j-1]
        return ma[m-1][n-1]

5. Reference

https://blog.csdn.net/Lu_gee/article/details/76938597
https://blog.csdn.net/fuxuemingzhu/article/details/79337352

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值