Sunday, December 27, 2015

[LeetCode] Coin Change

Wrong one with greedy way,
Example: [130, 110, 1] 220

public class Solution {
    public int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0) return -1;
        Arrays.sort(coins);
        return numberOfCoins(coins, coins.length - 1, amount);
    }
   
    private int numberOfCoins(int[] coins, int coinIndex, int remainAmount) {
        if (remainAmount == 0) return 0;
        if (coinIndex < 0) return -1;
        int numberOfCurrentCoin = remainAmount / coins[coinIndex];
        while (numberOfCurrentCoin >= 0) {
            int numberOfRemainCoin = numberOfCoins(coins, coinIndex-1, remainAmount - numberOfCurrentCoin * coins[coinIndex]);
            if (numberOfRemainCoin >= 0) return numberOfRemainCoin + numberOfCurrentCoin;
            numberOfCurrentCoin--;
        }
        return -1;
    }
}
Iterative solution:
https://leetcode.com/discuss/76217/java-both-iterative-recursive-solutions-with-explanations
public class Solution {
    public int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0) return -1;
        if (amount <= 0) return 0;
       
        int[] minCoins = new int[amount + 1];
        minCoins[0] = 0;
       
        for (int i = 1; i <= amount; i++) {
            minCoins[i] = Integer.MAX_VALUE;
            for (int coin : coins) {
                if (i - coin >= 0 && minCoins[i - coin] != Integer.MAX_VALUE) {
                    minCoins[i] = Math.min(minCoins[i], minCoins[i - coin] + 1);
                }
            }
        }
       
        return minCoins[amount] == Integer.MAX_VALUE ? -1 : minCoins[amount];
    }
}
Recursive solution:
public class Solution {
    public int coinChange(int[] coins, int amount) {
        if (coins == null || coins.length == 0) return -1;
        if (amount <= 0) return 0;
        HashMap<Integer, Integer> amountToCoinNumber = new HashMap<Integer, Integer>();
        return coinChangeHelper(coins, amount, amountToCoinNumber);
    }
   
    private int coinChangeHelper(int[] coins, int amount, HashMap<Integer, Integer> amountToCoinNumber){
        if (amount == 0) return 0;
        if (amount < 0) return -1;
        if (amountToCoinNumber.containsKey(amount)) return amountToCoinNumber.get(amount);
        int minimumNumber = -1;
        for (int coin : coins) {
            int remainNumber = coinChangeHelper(coins, amount - coin, amountToCoinNumber);
            if (remainNumber >= 0) {
                minimumNumber = Math.min(minimumNumber == - 1 ? Integer.MAX_VALUE : minimumNumber , remainNumber + 1);
            }
        }
        amountToCoinNumber.put(amount, minimumNumber);
        return amountToCoinNumber.get(amount);
    }
}

No comments:

Post a Comment