问题是无界背包问题的变化,其中你有相同价值但不同重量的物品。这个算法解决了这个问题,但我想优化它的性能。有没有人有任何建议?
def knapsack(capacity, bars)
if capacity == 0 || bars.nil? || bars[0].nil?
return 0
end
solutions = []
sum = 0
(1..capacity).each do |i|
break if sum > capacity
bars.combination(i).lazy.each do |comb|
sum = comb.reduce(&:+)
solutions << sum
end
end
solutions.select{|i| i <= capacity}.max
end