package leetcode;

/**
 * Created by Joshua on 6/8/17.
 * LC:322
 You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

 Example 1:
 coins = [1, 2, 5], amount = 11
 return 3 (11 = 5 + 5 + 1)

 Example 2:
 coins = [2], amount = 3
 return -1.

 Note:
 You may assume that you have an infinite number of each kind of coin.
 */
public class CoinChange3 {
    public int coinChange(int[] coins, int amount) {
        return dp(coins, amount);
    }

    public int dp(int[] coins, int amount) {
        if (amount == 0) {
            return 0;
        }

        int min = Integer.MAX_VALUE;
        for (int i=coins.length-1; i>=0; i--) {
            if (coins[i] > amount) {
                continue;
            }
            int count = dp(coins, amount-coins[i]);
            if (count >=0 && (count + 1) < min) {
                min = count + 1;
            }
        }
        return min == Integer.MAX_VALUE? -1: min;
    }



    public static void main(String[] args) {

        CoinChange3 c = new CoinChange3();
        int[] coins = new int[]{1,2,5};
        int count = c.coinChange(coins, 4);
        System.out.print(count);
    }
}

@@ -12,16 +12,42 @@
 tcode;%0A%0A
+import java.util.Arrays;%0A%0A
 /**%0A * C
@@ -624,32 +624,105 @@
 , int amount) %7B%0A
+        int%5B%5D cache = new int%5Bamount+1%5D;%0A        Arrays.fill(cache, -1);%0A
         return d
@@ -732,24 +732,31 @@
 oins, amount
+, cache
 );%0A    %7D%0A%0A  
@@ -786,35 +786,188 @@
 oins, int amount
-) %7B
+, int%5B%5D cache) %7B%0A        if (-1 != cache%5Bamount%5D) %7B%0A            return cache%5Bamount%5D;%0A        %7D%0A%0A        if (amount %3C 0) %7B%0A            return -1;%0A        %7D%0A
 %0A        if (amo
@@ -974,24 +974,50 @@
 unt == 0) %7B%0A
+            cache%5B0%5D = 0;%0A
             
@@ -1248,16 +1248,23 @@
 coins%5Bi%5D
+, cache
 );%0A     
@@ -1280,16 +1280,46 @@
  (count 
+!= Integer.MAX_VALUE && count 
 %3E=0 && (
@@ -1407,48 +1407,120 @@
     
-return min == Integer.MAX_VALUE? -1: min
+cache%5Bamount%5D = min;%0A        if (min != Integer.MAX_VALUE) %7B%0A            return min;%0A        %7D%0A        return -1
 ;%0A  
@@ -1525,17 +1525,16 @@
     %7D%0A%0A%0A
-%0A
     publ
@@ -1650,12 +1650,22 @@
 t%5B%5D%7B
-1,2,
+442,295,365,48
 5%7D;%0A
@@ -1704,17 +1704,20 @@
 (coins, 
-4
+8091
 );%0A     

add coin change 3