这是今天网易雷火笔试算法题涉及的一个知识点,考试时由于对python数组对象的引用不熟悉,导致没写出来。结束后写了写,目前没啥问题,先把代码贴出来,有空再来补充完整题面和代码注释
def putGems(price , k) -> int:
def copyTmp(tmp):
newTmp = []
for t in tmp:
newTmp.append(t.copy())
return newTmp
n = len(price)
res = []
def dfs(ind,numBag,tmp):
if ind==n-1 and numBag==k-1:
newTmp=copyTmp(tmp)
res.append(newTmp)
j=ind+1
if j>=n:
return
# 放在当前的背包里
newTmp = copyTmp(tmp)
newTmp[numBag].append(price[j])
dfs(j,numBag,newTmp)
# 放在下一个背包里
# newTmp = tmp.copy()
newTmp = copyTmp(tmp)
newTmp.append([price[j]])
dfs(j,numBag+1,newTmp)
dfs(0,0,[[price[0]]])
for r in res:
print(r)
scores = []
for r in res:
score = 0
for x in r:
score+=x[0]+x[len(x)-1]
scores.append(score)
minScore = min(scores)
maxScore = max(scores)
return maxScore-minScore
测试用例:
a=[2,6,9,5,10]
k=3
putGems(a,k)
运行结果: