package dynamic; import java.util.List; import java.util.ArrayList; import java.util.Scanner; import java.util.Collections; /** * Class that uses caching to solve ACM-NC 2004, Problem 1 * @author Dave Reed */ public class ChangeMaker2 { private static final int MAX_AMOUNT = 100; private static final int MAX_COINS = 10; private int[][] remember; private List coins; public ChangeMaker2(List coins) { this.coins = coins; remember = new int[ChangeMaker2.MAX_AMOUNT+1][ChangeMaker2.MAX_COINS]; for (int r = 0; r < ChangeMaker2.MAX_AMOUNT+1; r++) { for (int c = 0; c < ChangeMaker2.MAX_COINS; c++) { remember[r][c] = -1; } } } public int getChange(int amount) { return this.getChange(amount, coins.size()-1); } private int getChange(int amount, int maxCoinIndex) { if (maxCoinIndex < 0 || amount < 0) { return 0; } else if (this.remember[amount][maxCoinIndex] == -1) { if (amount == 0) { this.remember[amount][maxCoinIndex] = 1; } else { this.remember[amount][maxCoinIndex] = this.getChange(amount-this.coins.get(maxCoinIndex), maxCoinIndex) + this.getChange(amount, maxCoinIndex-1); } } return this.remember[amount][maxCoinIndex]; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int caseNum = 1; int numCoins = input.nextInt(); while (numCoins != -1) { ArrayList coins = new ArrayList(); for (int i = 0; i < numCoins; i++) { coins.add(input.nextInt()); } Collections.sort(coins); ChangeMaker2 cm = new ChangeMaker2(coins); if (caseNum > 1) { System.out.println(); } System.out.println("Case " + caseNum + ": " + cm.getChange(100) + " combinations of coins"); caseNum++; numCoins = input.nextInt(); } } }