LeetCode:322. 零钱兑换

今天药忘吃喽~ 2022-10-06 06:55 326阅读 0赞

链接:https://leetcode-cn.com/problems/coin-change/

标签:动态规划、完全背包问题、广度优先搜索

题目

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

你可以认为每种硬币的数量是无限的。

  1. 输入:coins = [1, 2, 5], amount = 11
  2. 输出:3
  3. 解释:11 = 5 + 5 + 1
  4. 输入:coins = [2], amount = 3
  5. 输出:-1
  6. 输入:coins = [1], amount = 0
  7. 输出:0
  8. 输入:coins = [1], amount = 1
  9. 输出:1
  10. 输入:coins = [1], amount = 2
  11. 输出:2
  12. 1 <= coins.length <= 12
  13. 1 <= coins[i] <= 231 - 1
  14. 0 <= amount <= 104

分析

此题和LeetCode第279题大致一样,可以参考这篇题解

可以使用BFS解决,也可以转换为完全背包问题解决。使用BFS解决的时候,注意选择合适的数据结构进行剪枝。具体的方法不再赘述,可以看上面的题解。

编码

BFS + 剪枝

  1. class Solution {
  2. public int coinChange(int[] coins, int amount) {
  3. Queue<Integer> queue = new LinkedList<>();
  4. queue.offer(amount);
  5. int length = coins.length, res = 0;
  6. boolean[] visited = new boolean[amount + 1];
  7. while (!queue.isEmpty()) {
  8. int len = queue.size();
  9. for (int j = 0; j < len; j++) {
  10. int num = queue.poll();
  11. if (num == 0) {
  12. return res;
  13. }
  14. for (int i = 0; i < length; i++) {
  15. if (num >= coins[i] && !visited[num - coins[i]]) {
  16. visited[num - coins[i]] = true;
  17. queue.offer(num - coins[i]);
  18. }
  19. }
  20. }
  21. res++;
  22. }
  23. return -1;
  24. }
  25. }

在这里插入图片描述

DP:

  1. class Solution {
  2. public int coinChange(int[] coins, int amount) {
  3. int[] dp = new int[amount + 1];
  4. Arrays.fill(dp, amount + 1);
  5. dp[0] = 0;
  6. for (int i = 1; i <= amount; i++) {
  7. for (int num : coins) {
  8. if (i >= num) {
  9. dp[i] = Math.min(dp[i - num] + 1, dp[i]);
  10. }
  11. }
  12. }
  13. return dp[amount] == (amount + 1) ? -1 : dp[amount];
  14. }
  15. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,326人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode 322 零钱兑换

    给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 示例 1

    相关 leetcode322 零钱兑换

    给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 示例 1

    相关 322. 零钱兑换

    > 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。 >

    相关 Leetcode 322. 零钱兑换

    题目重述 给你一个整数数组 coins ,表示不同面额的硬币;以及一个整数 amount ,表示总金额。 计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何

    相关 LeetCode-322. 零钱兑换

    [322. 零钱兑换][322.] 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币