# Leetcode No.322( Coin Change) 心得(Medium)

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

DP 的核心概念就是大問題有個最佳解，那我可以把它分解成一個或幾個小問題，這些小問題也有最佳解，依序下去。

F(amount) = F(amount-coins[i]) + 1

Recursive解法(Top-Down):

`public class Solution {`
`    public int coinChange(int[] coins, int amount) {                if (amount < 1) return 0;        return coinChange(coins, amount, new int[amount]);    }`
`    private int coinChange(int[] coins, int rem, int[] count) {        if (rem < 0) return -1;        if (rem == 0) return 0;        if (count[rem - 1] != 0) return count[rem - 1];        int min = Integer.MAX_VALUE;        for (int coin : coins) {            int res = coinChange(coins, rem - coin, count);            if (res >= 0 && res < min)                min = 1 + res;        }        count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;        return count[rem - 1];    }}`

Iteration解法(bottom-up):

`public class Solution {    public int coinChange(int[] coins, int amount) {        int max = amount + 1;                     int[] dp = new int[amount + 1];          Arrays.fill(dp, max);          dp[0] = 0;           for (int i = 1; i <= amount; i++) {            for (int j = 0; j < coins.length; j++) {                if (coins[j] <= i) {                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);                }            }        }        return dp[amount] > amount ? -1 : dp[amount];    }}`
Like what you read? Give ChingYuanYang a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.