// T(c^n) c coins.length, n =amount
/*#Recursive Method:#
https://discuss.leetcode.com/topic/32489/java-both-iterative-and-recursive-solutions-with-explanations
idea: dynamic programming: think of the last step we take. Suppose we have already found out the best way to sum up to amount a, then for the last step, we can choose any coin type which gives us a remainder r where r = a-coins[i] for all i's. For every remainder, go through exactly the same process as before until either the remainder is 0 or less than 0 (meaning not a valid solution). With this idea, the only remaining detail is to store the minimum number of coins needed to sum up to r so that we don't need to recompute it over and over again.*/
public int coinChange(int[] coins, int amount) {
if (amount < 1) return 0;
return helper(coins, amount, new int[amount]);
}
public int helper(int[] coins, int rem, int[] count) {
if (rem < 0) return -1; // not valid
if (rem == 0) return 0; // completed
if (count[rem - 1] !=0) return count[rem - 1]; // already computed, reuse
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int res = helper(coins, rem - coin, count);
if (res >= 0 && res < min)
min = 1 + res;
}
count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
return count[rem - 1];
}
// Iterative sol, we think in bottom0up manner. Suppose we have
// already computed all the minimum counts up to sum, what woule be the minimum count for sum+1?
public int coinChange(int[] coins, int amount) {
if (amount < 1) return 0;
int[] dp = new int[amount +1];
int sum = 0;
while (++sum <= amount) {
int min = -1;
for (int coin : coins) {
if (sum >= coin && dp[sum-coin] != -1) {
int temp = dp[sum-coin] + 1;
min = min<0 ? temp : (temp < min ? temp : min);
}
}
dp[sum] = min;
}
return dp[amount];
}**
322. Coin change
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- You are given coins of different denominations and a tota...
- You are given coins of different denominations and a tota...
- Coin Change给定一组硬币和一个目标金额,返回最少用几个硬币能凑出目标金额,如果不能返回-1。 数组dp用...