为什么我需要在递归中使用副本爬楼梯问题

问题描述

我正在解决经典面试中的一个问题,但遇到一个奇怪的问题。任务是通过给定number of stairs n和可能的移动(步骤)range(1,k)返回步骤的所有可能组合。只要将copy.copy成功的步骤组合之后再附加到all-solutions-array,我的解决方案就可以工作。有人知道为什么吗??

import copy
def climbingStaircase(n,k,successful_steps,steps_made):
    print(n,steps_made)

    # if there n is less than 0 --> return
    if n < 0:
        print('entering here')

        return
    # if n  == 0 -> we reached the top of the stairs
    if n == 0:

        successful_steps.append(copy.copy(steps_made))

        print('entering 0')
        print(n,steps_made)
        return

    for step in range(1,k+1):


        n -= step
        steps_made.append(step)


        climbingStaircase(n,steps_made) # 0,2,[[1,1,1]] [1,1]
        n += steps_made.pop() #
        # steps_made.pop()

    return

def countWays(n,k):
    successful_steps = []
    climbingStaircase(n,[])
    print(successful_steps)

countWays(4,2)

例如对于带有复制的4,2,我得到了解决方案:

[[1,1],[1,2],[2,2]]

如果我不使用复制功能,那么一切似乎都错了,似乎好像是通过编辑,添加和从steps_made弹出一样,我仍然在某种程度上影响着successful steps

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...