Accepted BFS w/ memoization


  • 0
    F

    class Solution {

    int min = Integer.MAX_VALUE;
    public int coinChange(int[] coins, int amount) {
        if (amount == 0) return 0;
        Queue<Integer> queue = new LinkedList<>();
        HashMap<Integer, Integer> hash = new HashMap<>();
        queue.add(amount);
        hash.put(amount, 0);
        while (!queue.isEmpty()) {
            int change = queue.poll();
            int level = hash.get(change);
            for (int coin: coins) {
                if (coin <= change) {
                    int remain = change - coin;
                    if (remain == 0) {
                        return level + 1;
                    }
                    if (!hash.containsKey(remain)) {
                        queue.add(remain);
                        hash.put(remain, level + 1);
                    }
                }
            }
        }
        return -1;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.