leet-code/src/main/java/leetcode/editor/cn/CoinChange.java
2021-08-03 15:13:00 +08:00

103 lines
2.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。
//
// 计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额,返回 -1 。
//
// 你可以认为每种硬币的数量是无限的。
//
//
//
// 示例 1
//
//
//输入coins = [1, 2, 5], amount = 11
//输出3
//解释11 = 5 + 5 + 1
//
// 示例 2
//
//
//输入coins = [2], amount = 3
//输出:-1
//
// 示例 3
//
//
//输入coins = [1], amount = 0
//输出0
//
//
// 示例 4
//
//
//输入coins = [1], amount = 1
//输出1
//
//
// 示例 5
//
//
//输入coins = [1], amount = 2
//输出2
//
//
//
//
// 提示:
//
//
// 1 <= coins.length <= 12
// 1 <= coins[i] <= 231 - 1
// 0 <= amount <= 104
//
// Related Topics 广度优先搜索 数组 动态规划
// 👍 1399 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
//322:零钱兑换
public class CoinChange {
public static void main(String[] args) {
//测试代码
Solution solution = new CoinChange().new Solution();
System.out.println(solution.coinChange(new int[]{1, 2, 5}, 11));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int coinChange(int[] coins, int amount) {
if (amount < 1) {
return 0;
}
return coinChange(coins, amount, new HashMap());
}
private int coinChange(int[] coins, int rem, Map<Integer, Integer> map) {
if (rem < 0) {
return -1;
}
if (rem == 0) {
return 0;
}
if (map.containsKey(rem)) {
return map.get(rem);
}
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int count = coinChange(coins, rem - coin, map);
if (count >= 0 && count < min) {
min = 1 + count;
}
}
min = (min == Integer.MAX_VALUE) ? -1 : min;
map.put(rem, min);
return min;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}