Unique Paths

博客探讨了在 m x n 网格中,位于左上角的机器人只能向下或向右移动,到达右下角的唯一路径数量问题。提到 m 和 n 最大为 100,并给出示例。还介绍了解决该问题的两种方法,递归因深度问题无法通过 LeetCode,后采用动态规划。

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:

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

方法一:递归

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        if m==1 and n>=1:
            return 1
        elif n==1 and m>=1:
            return 1
        else:
            return self.uniquePaths(m-1,n)+self.uniquePaths(m,n-1)

这段代码无法通过LeetCode,递归太深了改用方法二

方法二:动态规划(我也不知道算不算动态规划hiahia)

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        func = self.outer(m,n)
        return func
        
    def outer(self,m,n):
        UP=[[0]*(n+1) for i in range(m+1)]
        def calculate(a,b):      
            if a==1 and b>=1:
                return 1
            elif b==1 and a>=1:
                return 1
            elif UP[a][b]!=0:
                return UP[a][b]
            else:
                UP[a][b] =  calculate(a-1,b)+calculate(a,b-1)
                return UP[a][b]
        return calculate(m,n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值