package leetcode;

/**
 * https://leetcode.com/problems/coin-change-2/
 */
public class Problem518 {
    public int change(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        for (int i = 0; i < coins.length; i++) {
            for (int j = 1; j <= amount; j++) {
                int diff = j - coins[i];
                if (diff >= 0) {
                    dp[j] += dp[diff];
                }
            }
        }
        return dp[amount];
//        Integer[][] memo = new Integer[amount + 1][coins.length];
//        return coinChange(amount, coins, 0, memo);
    }

    private static int coinChange(int amount, int[] coins, int idx, Integer[][] memo) {
        if (amount <= 0) {
            if (amount == 0) {
                return 1;
            }
            return 0;
        }
        if (memo[amount][idx] != null) {
            return memo[amount][idx];
        }
        int count = 0;
        for (int i = idx; i < coins.length; i++) {
            count += coinChange(amount - coins[i], coins, i, memo);
        }
        memo[amount][idx] = count;
        return count;
    }

    public static void main(String[] args) {
        Problem518 prob = new Problem518();
        System.out.println(prob.change(5, new int[]{1, 2, 5})); // 4
//        System.out.println(prob.change(3, new int[]{2})); // 0
//        System.out.println(prob.change(10, new int[]{10})); // 1
//        System.out.println(prob.change(5000, new int[]{1})); // 1
    }
}
@@ -485,1017 +485,8 @@
 t%5D;%0A
-//        Integer%5B%5D%5B%5D memo = new Integer%5Bamount + 1%5D%5Bcoins.length%5D;%0A//        return coinChange(amount, coins, 0, memo);%0A    %7D%0A%0A    private static int coinChange(int amount, int%5B%5D coins, int idx, Integer%5B%5D%5B%5D memo) %7B%0A        if (amount %3C= 0) %7B%0A            if (amount == 0) %7B%0A                return 1;%0A            %7D%0A            return 0;%0A        %7D%0A        if (memo%5Bamount%5D%5Bidx%5D != null) %7B%0A            return memo%5Bamount%5D%5Bidx%5D;%0A        %7D%0A        int count = 0;%0A        for (int i = idx; i %3C coins.length; i++) %7B%0A            count += coinChange(amount - coins%5Bi%5D, coins, i, memo);%0A        %7D%0A        memo%5Bamount%5D%5Bidx%5D = count;%0A        return count;%0A    %7D%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem518 prob = new Problem518();%0A        System.out.println(prob.change(5, new int%5B%5D%7B1, 2, 5%7D)); // 4%0A//        System.out.println(prob.change(3, new int%5B%5D%7B2%7D)); // 0%0A//        System.out.println(prob.change(10, new int%5B%5D%7B10%7D)); // 1%0A//        System.out.println(prob.change(5000, new int%5B%5D%7B1%7D)); // 1%0A
     

Solve problem 518