Version 3: Bottom-up approach using filled slice with one above amount, which is one above max in scenario with denomination 1 * amount.
(coins []int, amount int)
| 5 | // Version 3: Bottom-up approach using filled slice with one above amount, |
| 6 | // which is one above max in scenario with denomination 1 * amount. |
| 7 | func coinChange(coins []int, amount int) int { |
| 8 | if amount == 0 { |
| 9 | return 0 |
| 10 | } |
| 11 | |
| 12 | // Fill the array with values larger than amount |
| 13 | // At most, denomination 1 coins would supply change for 'n' 'n' times |
| 14 | mins := make([]int, amount+1) |
| 15 | for i := range mins { |
| 16 | mins[i] = amount + 1 |
| 17 | } |
| 18 | |
| 19 | // It takes 0 coins to make up the amount of 0 |
| 20 | mins[0] = 0 |
| 21 | |
| 22 | for a := 1; a <= amount; a++ { |
| 23 | for c := 0; c < len(coins); c++ { |
| 24 | // coin is larger than current amount |
| 25 | if coins[c] > a { |
| 26 | continue |
| 27 | } |
| 28 | |
| 29 | // mins[a] is initially large enough to after being filled into slice above |
| 30 | mins[a] = int(math.Min(float64(mins[a]), float64(mins[a-coins[c]]+1))) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | if mins[amount] > amount { |
| 35 | return -1 |
| 36 | } |
| 37 | |
| 38 | return mins[amount] |
| 39 | } |
| 40 | |
| 41 | // Version 2: Bottom-up approach using MaxInt32 for min comparison |
| 42 | func coinChangeBottomUp1(coins []int, amount int) int { |
no outgoing calls