问题描述
我正在尝试解决问题 bestSum,它基本上找到了与目标值相加的最小元素数量,以下似乎工作正常,仅当使用 sub_num = [*(sub_num[:]),i]
添加 {{1} } 到 i
列表而不是使用 sub_num
我知道一个正在使用 sub_num.append(i)
而另一个不是,但无论如何我希望使用 deepcopy
方法获得相同的结果
sub_num.append(i)
使用附加给我 memo = {}
def how_sum(n,numbers):
if(n in memo):
return memo[n]
elif(n == 0):
return []
elif(n < 0):
return None
shortestcombination = None
for i in numbers:
sub_num = how_sum(n-i,numbers)
if ( sub_num != None ):
memo[n]= sub_num[:]
sub_num.append(i) #<-commenting this line and
#sub_num = [*(sub_num[:]),i] <-uncommenting this would give me correct ans
if( (shortestcombination == None) or (len(sub_num) < len((shortestcombination)))):
shortestcombination = sub_num[:]
if(shortestcombination != None):
memo[n] = shortestcombination[:]
else:
memo[n] = None
return shortestcombination
print(how_sum(7,[7]))
memo.clear()
print(how_sum(100,[1,2,5,25]))# ans should be [25,25,25]
memo.clear()
作为输出而不是第二个测试用例的 [25,25]
但如果我使用 [25,25]
会得到正确的答案
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)