代码随想录算法训练营第38天

322. 零钱兑换

如果求组合数就是外层for循环遍历物品,内层for遍历背包。

如果求排列数就是外层for遍历背包,内层for循环遍历物品。

这句话结合本题 大家要好好理解。

视频讲解:https://www.bilibili.com/video/BV14K411R7yv

https://programmercarl.com/0322.%E9%9B%B6%E9%92%B1%E5%85%91%E6%8D%A2.html

class Solution {
    public int coinChange(int[] coinValues, int totalAmount) {
        int impossible = Integer.MAX_VALUE;
        int[] minCoins = new int[totalAmount + 1];
        for (int i = 0; i < minCoins.length; i++) {
            minCoins[i] = impossible;
        }
        minCoins[0] = 0;
        for (int i = 0; i < coinValues.length; i++) {
            for (int j = coinValues[i]; j <= totalAmount; j++) {
                if (minCoins[j - coinValues[i]] != impossible) {
                    minCoins[j] = Math.min(minCoins[j], minCoins[j - coinValues[i]] + 1);
                }
            }
        }
        return minCoins[totalAmount] == impossible ? -1 : minCoins[totalAmount];
    }
}

279.完全平方数

本题 和 322. 零钱兑换 基本是一样的,大家先自己尝试做一做

视频讲解:https://www.bilibili.com/video/BV12P411T7Br

https://programmercarl.com/0279.%E5%AE%8C%E5%85%A8%E5%B9%B3%E6%96%B9%E6%95%B0.html

class Solution {
    public int numSquares(int target) {
        int impossible = Integer.MAX_VALUE;
        int[] combinations = new int[target + 1];
        for (int j = 0; j <= target; j++) {
            combinations[j] = impossible;
        }
        combinations[0] = 0;
        for (int sum = 1; sum <= target; sum++) {
            for (int i = 1; i * i <= sum; i++) {
                combinations[sum] = Math.min(combinations[sum], combinations[sum - i * i] + 1);
            }
        }
        return combinations[target];
    }
}

139.单词拆分

视频讲解:https://www.bilibili.com/video/BV1pd4y147Rh

https://programmercarl.com/0139.%E5%8D%95%E8%AF%8D%E6%8B%86%E5%88%86.html

import java.util.List;

class Solution {
    public boolean wordBreak(String sentence, List<String> dictionary) {
        boolean[] canBreak = new boolean[sentence.length() + 1];
        canBreak[0] = true;

        for (int index = 1; index <= sentence.length(); index++) {
            for (String word : dictionary) {
                int wordLength = word.length();
                if (index >= wordLength && canBreak[index - wordLength] && word.equals(sentence.substring(index - wordLength, index))) {
                    canBreak[index] = true;
                    break;
                }
            }
        }

        return canBreak[sentence.length()];
    }
}

关于多重背包,你该了解这些!

https://programmercarl.com/%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80%E5%A4%9A%E9%87%8D%E8%83%8C%E5%8C%85.html

背包问题总结篇!

https://programmercarl.com/%E8%83%8C%E5%8C%85%E6%80%BB%E7%BB%93%E7%AF%87.html

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值