问题是:“你在爬楼梯。爬到山顶需要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]“我们为什么要用两个‘返回记忆’?我想,”
if memo.get(n):
memo[n] = climb(n-1, memo) + climb(n-2, memo)
return memo[n]“这是回忆录思想在这里描述的方式。
此外,如果我解释代码的评论是错误的,请纠正我,因为我是编程新手。如果有任何其他更简单和更好的优化方法,我应该实施来解决这个问题,那么请告诉我。
我之前发过一些其他问题,一些人用粗鲁的口吻回答,尽管我明白,我在这里看到的帮助是为了自学编程。我知道他们的知识是非常先进的,而且我还远没有达到这个水平。因此,如果我能够理解代码并从回答问题的人那里学习编程,我会很感激的。
发布于 2021-11-02 17:40:15
第一个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]但是在第二个返回语句中,它给出了存储在climb(n-1, memo) + climb(n-2, memo)上并在代码执行中从未执行过的memo[n]的计算。
我建议您观看这些视频,以便更深入地了解递归是如何工作的:
https://stackoverflow.com/questions/69814704
复制相似问题