我正在尝试解决一个问题。我有一些重量:
[2,7,20,70,200,700]
。给定一个输入,例如1507
,它应该返回这些重量的最佳组合。在这种情况下,最佳组合应该是[700,200,200,200,200,7]
。不幸的是,我的算法返回了[700, 700, 70, 20, 7, 2, 2, 2, 2, 2]
。当我说“最佳”时,我的算法应该使用尽可能少的重量。func solve(_ targetValue: Int, weights: inout [Int]) -> [Int] {
// The used weights to store
var usedWeights: [Int] = []
// The current total value for the calculation
var total = targetValue
// If target value is 0 add it to the array and just return it
if targetValue == 0 { usedWeights.append(0); return usedWeights }
// Loop through the weights
for weight in weights.reversed() {
while weight <= total {
total -= weight
usedWeights.append(weight)
}
} // If still weights are not found call the function recursively again but remove the last element before
if total != 0 {
weights.removeLast()
return solve(targetValue, weights: &weights)
}
return usedWeights
}
var newWeights: [Int] = [2,7,20,70,200,700]
print(solve(1507, weights: &newWeights))
我应该怎么解决这个问题?我做错了什么吗?重要的是使用回溯法来解决它。非常感谢你的帮助。