Given an array of coin denominations coins and a total, find all possible combinations that result in the minimum number of coins summing to the total. In my solution I keep a running track of the minimum number of coins at table[i] that sum to i. I'm not sure exactly how this would be modified to store the actual coins that sum to i and make sure that both possibilities in this case are included. I've looked at other code on stack overflow, but I've only found code that will print any one of the optimal solutions.
Input: minimum_coins(10, [2,3,5,6,7,8])
Output: [[5,5],[2,8]]
INT_MAX = 2 ** 63 - 1
def minimum_coins(total, coins)
table = Array.new(total + 1)
table[0] = 0
(1..total).to_a.each do |i|
table[i] = INT_MAX
end
(1..total).to_a.each do |i|
(0..coins.length-1).to_a.each do |j|
if coins[j] <= i
sub_res = table[i-coins[j]]
if sub_res != INT_MAX && sub_res + 1 < table[i]
table[i] = sub_res + 1
end
end
end
end
puts table.inspect
end
minimum_coins(10, [2,3,5,6,7,8])