我正在解决一个类似的背包问题:这是打印出价值高于数字但重量低于限制的对象的第一个组合。
我试过了:
value = [10, 8, 7, 6, 4]
weight = [8, 4, 3, 3, 1]
name = ['A','B','C','D','E']
Wlimit = 8
Vlimit = 8
def ID(maxDepth):
for i in range(1, maxDepth):
knapsack = []
if (DFS(knapsack, 0, 0, i)):
return True
else:
print("cannot find solution")
return False
def DFS(knapsack, currentValue, currentWeight, maxDepth):
# If reached the maximum depth, stop recursing.
if maxDepth <= 0 : return False
if currentValue >= Vlimit and currentWeight <= Wlimit:
print(knapsack)
return True
for i in range(len(name)):
if name[i] not in knapsack:
if ((currentWeight + weight[i]) < Wlimit):
knapsack.append(name[i])
DFS(knapsack, currentValue + value[i], currentWeight + weight[i], maxDepth - 1)
knapsack = knapsack[:-1]
DFS(knapsack, currentValue, currentWeight, maxDepth - 1)
else:
DFS(knapsack, currentValue, currentWeight, maxDepth - 1)
return False
我知道这棵树看起来像这样
但我不知道如何用正确的逻辑修复代码希望有人能帮我一把。
谢谢!!