public class Coins_memo { static int[] ans; static int M(int[] v, int j) { int sol; int k, min; /* --------------------------- Base cases --------------------------- */ if ( j == 0 ) { return(0); } if ( ans[j] > 0 ) { return(ans[j]); } sol = M(v, j - 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]); // 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); System.out.println("Min # coins to make change for " + C + " = " + r); } }