我在解决经典面试中的一个问题时遇到了一个奇怪的问题。任务是通过给定的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
目前没有回答
相关问题 更多 >
编程相关推荐