Epic - Coin Change

Something cost $10.25 and the customer pays with a $20 bill, the program will print out the most efficient "change-breakdown" which is 1 five, 4 ones, and 3quarters. Find the minimum number of coins required to make change for a given sum (given unlimited cumber of N different denominations coin)

动态规划:dp数组存储的元素表示需要达到该下标值时所需要的最小硬币数,转移方程为 dp[i] = min(dp[i],dp[i-x]+1)

def coin_change(coin,sum)

  dp = Array.new(sum+1,sum) #the sum is integer

  dp[0] = 0

  (1..sum).each {|i| coin.each {|x| dp[i] = [dp[i],dp[i-x]+1].min if x <= i}}

  dp[-1]

end

你可能感兴趣的:(change)