原题链接:322. Coin Change
"Thinking-java"
The subject examines the dynamic planning. Perhaps at first it was easy to think of greedy algorithm, but the greedy algorithm in some cases is not tenable, such as coins = [1, 3, 5, 6], to amount = 11, with the greedy return 3, actually the least 2 (3 + 5). As a result of dynamic planning, with DP storage number of coins, Dp[i] said that the sum of money I need the minimum number of coins, then the sum of Money amount the minimum number of coins: fixed money for coins[j] a coin, the other amount of money for AMOUNT-COINS[J] its number is Dp[amou Nt-coins[j]],j traverse from 0 to Coins.length-1:
public int coinchange (int[] coins, int amount) {
int[] dp = new Int[amount + 1];
for (int i = 1; I <= amount i++) {
dp[i] = 0x7fffffff;
for (int j = 0; J < Coins.length; J +)
if (i >= coins[j] && dp[i-coins[j]]!= 0x7fffffff) //①
Dp[i] = Math.min (Dp[i], Dp[i-coins[j]] + 1);
}
return Dp[amount] = = 0x7fffffff? -1:dp[amount];
}
180/180 Test cases passed. Runtime:24 ms Your Runtime beats 78.00% of javasubmissions.
Welcome optimization.
"Optimization" by--Kabila, 2016.5.19
Thank you very much enthusiastic Bo Friends Kabila proposed optimization program, its code is as follows:
public int coinchange (int[] coins, int amount) {
int[] dp = new Int[amount + 1];
for (int i = 1; I <= amount i++) dp[i] = 0x7fff_fffe;
for (int coin:coins)
for (int i = coin i <= amount i++)
dp[i] = math.min (dp[i), Dp[i-coin] + 1);
return Dp[amount] = = 0x7fff_fffe? -1:dp[amount];
}
180/180 Test cases passed. Runtime:15 ms Your Runtime beats 96.29% of javasubmissions.
The scheme is indeed very ingenious, using 0x7fff_fffe instead of 0x7fff_ffff, while making coins i = coin, so that the original code ① to eliminate the judgment, so as to achieve the optimization effect.