public class Coins_memo_print { static int min_ans = Integer.MAX_VALUE; static String print_ans; static int[] ans; static int M(int[] v, int j, int n, String s) { int sol; int k, min; /* --------------------------- Base cases --------------------------- */ if ( j == 0 ) { if ( n <= min_ans ) { min_ans = n; print_ans = s; } return(0); } if ( ans[j] > 0 ) { return(ans[j]); } sol = M(v, j - v[0], n+1, s + ";" + v[0]); // Try one coin of denomination 0 // with value v[0] min = sol + 1; // Best solution so far... for ( k = 1; k < v.length; k++ ) { /* -------------------------------------------- Check if we can use the k-th denomination -------------------------------------------- */ if ( v[k] <= j ) { /* ------------------------ Divide step ------------------------ */ sol = M(v, j - v[k], n+1, s + ";" + v[k]); // Try one coin of denomination k // with value v[k] /* --------------------------------------- Conquer: solve original problem using solution from smaller problems --------------------------------------- */ if ( sol + 1 < min ) min = sol + 1; // New best solution so far } } ans[j] = min; return(min); // Return best solution } public static void main(String[] args) { // int[] v = {1, 5, 10, 25, 50, 100, 500}; int[] v = {1, 3, 9, 19, 26}; int C, r; C = 65; ans = new int[C+1]; r = M(v, C, 0, ""); System.out.println("Min # coins to make change for " + C + " = " + r); System.out.println("Min_ans = " + min_ans); System.out.println(); System.out.println("Denominations used:"); System.out.println(print_ans); System.out.println(); System.out.println(); } }