Leetcode 332 Change Exchange Detailed Java

Given coins of different denominations and a total amount. Write a function to calculate the minimum number of coins required to complete the total amount. If no coin combination completes the total amount, -1 is returned.

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
Explanation:
You can think that the number of each coin is infinite.

 The idea of ​​the knapsack problem, first of all, an ans array, how many coins should be used to store the money of the current index, the main idea is, either the number of coins needed to be stored in the current index, or the amount of the current index value needs the current ans[index The number of coins stored in ], or ans[index-coins[i]]+1, this is if the coins with the current denomination coins[i] are added, then the current amount is index-coins[i], so check The number of coins stored in ans[index-coins[i]], plus the current coin, is the number of coins required when the amount is index, and the minimum value of these two possibilities is the minimum required number of coins.

The recursion equation is as follows:

ans[i] = Math.min(ans[i],ans[i-coins[j]]+1);

The calculation process is shown in the figure below:

The last ans[amount] stores the number of coins required to exchange the amount.

code show as below:

class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] ans = new int[amount+1];
        Arrays.fill(ans,amount+1);
        ans[0] = 0;
        for(int j = 0;j<coins.length;j++){
            for(int i=1;i<ans.length;i++){
                if(i>=coins[j]){
                    ans[i] = Math.min(ans[i],ans[i-coins[j]]+1);
                }
            }
        }
        return ans[amount]>amount?-1:ans[amount];
    }
}

 

Guess you like

Origin blog.csdn.net/qq_23128065/article/details/104729144