322. Coin Change

Problem:
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:
Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.

Analysis:
State dp[i]: How many coins to make up amount i.
Transition: current amount is larger than current coin, dp[i] = min(ap[i], dp[i - coins[j]]. For instance the amount is 11, dp[10] = 2, the coin with value 1 can make up 11 after 10, So we add 1 to dp[10].
Solution:
Initialize dp to amount + 1 is to make sure prev amount, i - coins[j], has been fill. Take [2], 3 as an example. if we set dp[3] to dp[3 - 2] + 1, then dp[1] is not possible. The amount + 1 is a little it misleading, it should be value large enough. Clearly, the smallest qualified value is amount  + 1.

Comparing dp[i] with dp[i - coins[j]] + 1 makes the min coin change possible. 
class Solution {
    public int coinChange(int[] coins, int amount) {
        if (coins == null)
            return -1;
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        for (int  i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.length; j++) {
                if (i >= coins[j]) {
                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array