问题描述
我正在解决经典面试中的一个问题,但遇到一个奇怪的问题。任务是通过给定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 (将#修改为@)