|
| 1 | +import java.util.HashMap; |
| 2 | + |
| 3 | +/** |
| 4 | + * given an array of different coin sizes and a target amount you want to break down |
| 5 | + * in how many different ways can you break it down into coins? |
| 6 | + * Also every coin can only be used once |
| 7 | + * <p> |
| 8 | + * this solution assumes coin values are whole integers |
| 9 | + */ |
| 10 | + |
| 11 | +// using every coin once - how many different sets of coins do you have? |
| 12 | +public class CoinChange { |
| 13 | + |
| 14 | + private static int howManySets(int[] arr, int target, HashMap<Integer, Integer> memo, int index) { |
| 15 | + // if we have done this calculation before just return the result |
| 16 | + if (memo.containsKey(target)) |
| 17 | + return memo.get(target); |
| 18 | + |
| 19 | + if (index >= arr.length && target != 0) { |
| 20 | + return 0; |
| 21 | + } |
| 22 | + |
| 23 | + if (target - arr[index] >= 0) { |
| 24 | + // possibilities if we choose to include this coin value |
| 25 | + int possiblity1 = howManySets(arr, target - arr[index], memo, index + 1); |
| 26 | + if (!memo.containsKey(target - arr[index])) |
| 27 | + memo.put(target - arr[index], possiblity1); |
| 28 | + |
| 29 | + // and possibilities if we chose to skip this coin |
| 30 | + int possiblity2 = howManySets(arr, target, memo, index + 1); |
| 31 | + if (!memo.containsKey(target)) |
| 32 | + memo.put(target, possiblity2); |
| 33 | + |
| 34 | + return possiblity1 + possiblity2; |
| 35 | + } else { |
| 36 | + int possiblity2 = howManySets(arr, target, memo, index + 1); |
| 37 | + if (!memo.containsKey(target)) |
| 38 | + memo.put(target, possiblity2); |
| 39 | + return possiblity2; |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + } |
| 45 | + |
| 46 | + public static void main(String[] args) { |
| 47 | + //array of different coins we can use |
| 48 | + int[] arr = {2, 4, 6, 10, 8}; |
| 49 | + |
| 50 | + int target = 12; |
| 51 | + |
| 52 | + // key - what is the target |
| 53 | + // value - how many sets |
| 54 | + HashMap<Integer, Integer> memo = new HashMap<>(); |
| 55 | + |
| 56 | + //if the value is broken up and you are left with 0$ to break down -> there is only one possibility |
| 57 | + memo.put(0, 1); |
| 58 | + |
| 59 | + System.out.println(howManySets(arr, target, memo, 0)); |
| 60 | + } |
| 61 | +} |
0 commit comments