topic:
Analysis: If you use the greedy method, the solution may not be the optimal solution
. For example, [1,1,3,,4][1,1,4,] and [3,3] are obviously wrong.
We should use the dynamic programming method to solve the problem.
The face value of the banknote is [1,2,5] and the amount is 11
dp[i], which represents the optimal solution of the amount i (that is, the smallest number of sheets used)
. The optimal solution of the amount 1 to 11 (the least) is stored in the array dp[] Number of banknotes used)
When calculating dp[i], dp[0], dp[1], dp[i-1] are all known
The amount i can be summarized as follows:
i-1 and coins[0] form
i-2 and coins[1] form
i-3 and coins[2]
That is to say, the state i can be obtained by the state i-1, i-2, i-5, and 3 state transitions, so:
dp[i]=min(dp[i-1],dp[i-2],dp[i- 5])+1
i-1, i-2, i-5 indicate the number of banknotes needed to look at the front position, +1 is to add the current one, and its value can be one of 1 2 5 7 to get the current sum The least used total.
public int coinChange(int[] coins, int amount) {
int len = coins.length;
if (len == 0 || amount<0)
return -1;
if (amount==0)
return 0;
int [] dp = new int[amount+1];
for (int i = 0; i <= amount; i++){
dp[i] = -1;
}
for (int i = 0; i< len;i++){
if(coins[i] == amount)
return 1;
if(coins[i] < amount)
dp[coins[i]] = 1;
}
// State Transfer Function
for(int i = 1; i <= amount;i++){
for (int j = 0; j < len; j++){
if (i - coins[j] >= 0 && dp[i - coins[j]] != -1){
if (dp[i] == -1 || dp[i] > dp[i - coins[j]] + 1){
dp[i] = dp[i - coins[j]] + 1;
}
}
}
}
return dp[amount];
}