ref:https://leetcode.com/problems/coin-change/
is a complete knapsack problem, you can review the knapsack problem again.
01 Backpack:
For each item
For Amount...cost[item]
F[V] = Max{f[v], F[v-cost[item]] + Weight[item]}
Because 01 backpack each item can only be used once, so amount to calculate from the back forward, because the comparison of the time with F[v] and F[v-cost[item]], the second there is a minus, so back to calculate, the result is not used in front of
Full backpack
For each item
For Cost[item]...amout
F[V] = Max{f[v], F[v-cost[item]] + Weight[item]}
Because each item can be used many times, so amount from small to large walk, because every time after the results are used in the previous results.
If you require a full backpack, set f[0] to 0 and the others to Integer.min_value
The topic is discussed below, the question is a complete knapsack problem, coins[] is Cost[],amount is the capacity of the backpack, asked the backpack just full, weight is all the item is 1
The difference is that the traditional knapsack problem is to ask for the maximum weight, but the topic is to seek the minimum weight, so there are differences in initialization. Dp[0] = 0, and all that remains is integer.max_value.
1 Public intCoinchange (int[] coins,intamount) {2 if(Coins.length = = 0 | | Amount < 0) {3 return-1;4 }5 int[] DP =New int[Amount+1];6 Arrays.fill (DP, integer.max_value);7Dp[0] = 0;8 for(inti = coins.length-1; I >= 0; i--) {9 for(intj = Coins[i]; J <= Amount; J + +) {Ten if(Dp[j-coins[i]]! =integer.max_value) { OneDP[J] = Math.min (Dp[j], Dp[j-coins[i]] + 1); A } - } - } the returnDp[amount] = = Integer.max_value? -1: Dp[amount]; -}
322. Coin Change