TypechoJoeTheme

IT技术分享

统计

[LeetCode 322] Coin Change [Java]

2017-10-16
/
0 评论
/
743 阅读
/
正在检测是否收录...
10/16

1. Description

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.

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

2. Runtime Distribution

3. Submission Details

4. Example

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


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

5. Code

import java.util.Arrays;

public class LeetCode0322 {
    public int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0 || amount <= 0) {
            return 0;
        }

        long[] dp = new long[amount + 1];

        Arrays.fill(dp, Integer.MAX_VALUE);

        dp[0] = 0;

        for (int i = 0; i < dp.length; i++) {
            for (int j = 0; j < coins.length; j++) {
                if ((long)i + coins[j] <= amount) {
                    dp[i + coins[j]] = Math.min(dp[i + coins[j]], dp[i] + 1);
                }
            }
        }

        return dp[amount] >= Integer.MAX_VALUE ? -1 : (int) dp[amount];
    }

    public static void main(String[] args) {
        LeetCode0322 leetcode = new LeetCode0322();
        int[] coins = new int[] { 2147483647 };
        System.out.println(leetcode.coinChange(coins, 2));
    }
}
DP
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1154/(转载时请注明本文出处及文章链接)