【发布时间】:2018-05-17 19:00:26
【问题描述】:
我正在尝试解决一个问题。我有一些重量。 [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))
我该如何解决这个问题?我究竟做错了什么?重要的是使用回溯来解决它。非常感谢您的帮助。
【问题讨论】:
-
仅供参考 - 您不需要检查 1、3 和 5。此外,这些权重可能会被传入。
-
是的,没错,但我检查了它,因为我只有上述重量。
-
取出这些支票。不管你有没有这些重量。您也没有许多其他值的权重。
-
但是如果我不检查它会使用很多权重
标签: swift algorithm backtracking