Leetcode - 322 - Coin Change

来自牛奶河Wiki
阿奔讨论 | 贡献2024年4月25日 (四) 11:22的版本 (创建页面,内容为“322. Coin Change * Medium You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return 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. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Expl…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

322. Coin Change

  • Medium

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return 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.

You may assume that you have an infinite number of each kind of coin.

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

Example 3:
Input: coins = [1], amount = 0
Output: 0

Constraints:
    1 <= coins.length <= 12
    1 <= coins[i] <= 231 - 1
    0 <= amount <= 104

Solution

The solution of the original problem consists of the optimal solution of the subproblem. To conform to the "optimal substructure", the subproblems must be independent of each other.

  • When coin=1, dp[6] = 1 + the optimal solution of dp[5].
  • When coin=2, dp[6] = 1 + dp[4].
  • When coin=5, dp[6] = 1 + dp[1].

After iterating through all coins(1, 2, 5), the optimal solution of dp[6] is selected by min.

  • the state transition equation: dp[i] = min(dp[i], 1 + dp[i-coin])

Java

 public class lc322 {
    public static int coinChange(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, amount + 1);
        dp[0] = 0;
        for (int i=1; i<=amount; i++) {
            for (int c : coins) {
                if (i >= c) {
                    if (dp[i] > dp[i-c]+1) dp[i] = dp[i-c]+1;
                }
            }
        }

        if (dp[amount] > amount) {
            return -1;
        } else {
            return dp[amount];
        }
    }

    public static void main(String[] args) {
        int[] coin1 = {1, 2, 5};
        int amount = 11;

        System.out.println(coinChange(coin1, amount));
    }
}