首页 > 解决方案 > 关于爬楼梯记忆自上而下方法的问题

问题描述

问题是:“你正在爬楼梯。到达顶部需要 n 步。每次你可以爬 1 或 2 步。你可以通过多少不同的方式爬到顶部?”

自顶向下记忆方法的代码是:

class Solution:
    def climbStairs(self, n: int) -> int:
        def climb(n, memo): #So, here our function will have two values. n is the number of steps and let's call it memo. Memo will be used to show the return value that reduces the recursive calls
            if n < 0: #edge case
                return 0 #Return None
            if n == 0:
                return 1 #There is an error while executing the program and it is not performing what it was intended to do
            if memo.get(n): #if the number of steps n are taken which is from 1 to 45, then we can use the get method to find the number of steps
                return memo[n] #to find the number of recursive calls we will use the memoization method which is
            memo[n] = climb(n-1, memo) + climb(n-2, memo) #memoization will return the number of steps be using the previous two steps
            return memo[n]#return the value that reduces the recursive calls
        return climb(n, {})

我对这些线条感到困惑“

if memo.get(n):
return memo[n]
memo[n] = climb(n-1, memo) + climb(n-2, memo)
return memo[n]

“为什么我们使用两个'return memo[n]'?我想,”

if memo.get(n):
memo[n] = climb(n-1, memo) + climb(n-2, memo)
return memo[n]

"是记忆化想法在这里的描述。

另外,如果我解释代码的评论有误,请纠正我,因为我是编程新手。如果我应该实施任何其他更简单、更好优化的方法来解决这个问题,那么请告诉我。

我之前发布了一些其他问题,尽管了解我在这里寻求帮助以自学编程的事实,但有些人以粗鲁的语气回答。我知道他们的知识很先进,和我相差甚远。因此,如果我能理解代码并从回答问题的人那里学习编程,我将不胜感激。

标签: pythonrecursiondynamic-programmingmemoization

解决方案


第一个 return 语句在if条件内,当它已经计算时它返回一个值,以便不计算 2 次或更多次相同的操作。

if memo.get(n): #This if is basically checking if the code has already computed the function in n
 return memo[n]

#This line never executes if the code has already returned memo[n] in the if condition used to NOT compute multiple times the same operation
memo[n] = climb(n-1, memo) + climb(n-2, memo) 
return memo[n]

但是在第二个 return 语句中,它给出了climb(n-1, memo) + climb(n-2, memo)存储在memo[n]代码执行中之前从未完成过的计算。

我建议您观看这些视频以更深入地了解递归的工作原理:
视频 1
视频 2


推荐阅读