Replacing recursion with while loop (stair climbing puzzle): Python

天大地大妈咪最大 提交于 2019-12-05 21:57:36

This amounts to the top-down (recursive) approach vs. the bottom-up (iterative) approach for dynamic programming.

Since you know that for input n you need all values of stairs(p) for 0 <= p <= n. You can iteratively compute stairs(p) starting at p = 0 until you reach p = n, as follows:

def stairs(n):
    table = [1, 1]  # p = 0 and p = 1
    for i in range(2, n + 1):
        table.append(table[i - 2] + table[i - 1])
    return table[n]

A different approach than @univerio is to use a list as stack:

def stairs_it(n):
    res = 0
    stack = [n]
    while len(stack) > 0:
        curr = stack[0]
        stack.remove(curr)
        if curr == 0:
            res += 0
        elif curr == 1:
            res += 1
        elif curr == 2:
            res += 2
        else:
            stack.append(curr-1)
            stack.append(curr-2)
    return res
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!