python - 关于爬楼梯记忆自上而下方法的问题
问题描述
问题是:“你正在爬楼梯。到达顶部需要 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]
"是记忆化想法在这里的描述。
另外,如果我解释代码的评论有误,请纠正我,因为我是编程新手。如果我应该实施任何其他更简单、更好优化的方法来解决这个问题,那么请告诉我。
我之前发布了一些其他问题,尽管了解我在这里寻求帮助以自学编程的事实,但有些人以粗鲁的语气回答。我知道他们的知识很先进,和我相差甚远。因此,如果我能理解代码并从回答问题的人那里学习编程,我将不胜感激。
解决方案
第一个 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]
代码执行中之前从未完成过的计算。
推荐阅读
- mysql - 无法使用 docker-compose setup 运行 artisan migrate
- angular - 操作 DOM 和 TS 数据
- sql - 如何连接两个不同表的列
- java - 全局添加/删除侦听器到所有活动
- twitter-bootstrap - 如何避免 Vue.js v-for 复制引导行
- vbscript - 如何使用 VBScript 临时阻止所有宏运行和编辑 xlsm 文件?
- swift - 如何分离在另一个范围中定义的侦听器?
- eclipse - 可以在 Windows 和 Linux 中使用二进制包吗?
- reactjs - 如何在未定义 slug 上显示未找到页面?/ 反应路由器 DOM
- java - 助手:无法下载marven库