Coin change problem with infinite number of coins of each denomination

后端 未结 5 708
感动是毒
感动是毒 2020-12-09 07:19

I want to know the idea of algorithm for the coin change problem where each denomination has infinte number of coins. Means how to apply DP (like the standard coin change pr

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 07:34

    Regarding the brute force.

    It is called "greedy algorithm" - you always take the biggest coin which is not greater than the value you need to represent.

    pseudo code, returns the number of coins needed to represent value, if we can use each one infinite number of times

    int[] greedy(int value, int[] coins) {
       int[] ans = ...;
       int v = coins.length - 1;
       int left = value;
       while (left > 0 && v >= 0) {
           if (coins[v] <= left) {
               ans.push(coins[v]);
           } else { 
               v--;
           }
       }
       return left == 0 ? ans : //representation impossible, 
                                //so you better do something;
    }
    

    pseudo code, returns the number of coins needed to represent value, if we can use each one infinite number of times

    int f(int value, int[] coins) {
       int[] memo = new int[value + 1];
       Arrays.fill(memo, 1234567);
       memo[0] = 0;
       for (int coin : coins)
           for (int i = 0; i + coin <= value; i++)
               memo[i + coin] = min(memo[i + coin], memo[i] + 1);
       return memo[value];
    }
    

    to know which coins to take, start from the end: if memo[value] = 3, then you check all coins and find such coin that memo[value - coin] == 2, continue from (value - coin) until you reach 0.

提交回复
热议问题