I have unlimited 4 types of coins in cent: [1, 5, 25, 50]. How to pick EXACT 48 coins to make a exact 1 dollar change?(in any one valid way)
I know how to solve this recursively, but is it possible to solve it using DP? How? Thanks!
The possible solution may be the following (Haskell):
change d coins | null coins = []
| d==0 = []
| d>=coin = coin:change (d-coin) coins
| otherwise = change d (tail coins) where
coin = head coins
Note that:
Here are some results:
*Main> change 100 [50, 25, 5, 1]
[50,50]
*Main> change 99 [50, 25, 5, 1]
[50,25,5,5,5,5,1,1,1,1]
*Main> change 75 [50, 25, 5, 1]
[50,25]
If you have limitation on number of coins used in solution:
exactChange d coins n
| d==0 && n==0 = [[]]
| d>0 && n==0 = []
| d==0 && n>0 = []
| null coins = []
| d>=coin = useFirstCoinSolutions ++ skipFirstCoinSolutions
| otherwise = skipFirstCoinSolutions where
coin = head coins
rest = tail coins
useFirstCoinSolutions = map (\x->coin:x) $ exactChange (d-coin) coins (n-1)
skipFirstCoinSolutions = exactChange d rest n
This gives the following result:
*Main> exactChange 100 [50, 25, 5, 1] 48
[[25,25,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[25,5,5,5,5,5,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],[5,5,5,5,5,5,5,5,5,5,5,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
So, it gives all possible solutions for change 100 cent with exact 48 coins
Explanation