为什么我需要在递归中使用复制(爬楼梯问题)

2024-05-29 08:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在解决经典面试中的一个问题时遇到了一个奇怪的问题。任务是通过给定的number of stairs n和可能的移动(步骤)range(1,k)返回所有可能的步骤组合。我的解决方案只有在将copy.copy成功步骤组合添加到all-solutions-array之前才有效。有人知道原因吗

import copy
def climbingStaircase(n, k, successful_steps, steps_made):
    print(n, k, successful_steps, 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, k, successful_steps, steps_made)
        return

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


        n -= step
        steps_made.append(step)


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

    return

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

countWays(4,2)

例如,对于4,2和copy,我得到了解决方案:

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

如果我不使用复制功能,一切似乎都错了,似乎通过编辑、添加和从steps_made弹出,我仍然在以某种方式影响successful steps


Tags: ofreturnifdefstep步骤range解决方案

热门问题