【发布时间】:2021-12-17 05:36:38
【问题描述】:
问题是:“你正在爬楼梯。到达顶部需要 n 步。 每次您可以爬 1 或 2 级台阶。你可以通过多少种不同的方式登顶?”
Top-down memoization 方法的代码是:
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]
" 是记忆化想法在这里的描述。
另外,如果我的 cmets 解释代码有误,请纠正我,因为我是编程新手。如果我应该实施任何其他更简单、更好优化的方法来解决这个问题,请告诉我。
我之前发布了一些其他问题,尽管理解我在这里寻求帮助以自学编程的事实,但有些人以粗鲁的语气回答。我知道他们的知识很先进,和我相差甚远。所以,如果我能理解代码并从回答问题的人那里学习编程,我将不胜感激。
【问题讨论】:
标签: python recursion dynamic-programming memoization