算法D44 | 动态规划6 | 完全背包 518. 零钱兑换 II 377. 组合总和 Ⅳ

力扣上没有纯粹的完全背包的题目,所以大家看本篇了解一下 完全背包的理论
后面的两道题目,都是完全背包的应用,做做感受一下

完全背包

视频讲解:带你学透完全背包问题! 和 01背包有什么差别?遍历顺序上有什么讲究?_哔哩哔哩_bilibili

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%AE%8C%E5%85%A8%E8%83%8C%E5%8C%85.html

518. 零钱兑换 II

视频讲解:动态规划之完全背包,装满背包有多少种方法?组合与排列有讲究!| LeetCode:518.零钱兑换II_哔哩哔哩_bilibili

代码随想录

Python:

518和377两个题适合一起品一品,两层forloop的顺序对于结果是由影响的,如果先遍历物品后遍历背包,结果是组合,即518题;反之,如果先遍历背包后遍历物品,结果是排列,即377题。

python 复制代码
class Solution:
    def change(self, amount: int, coins: List[int]) -> int:
        dp = [0] * (amount+1)
        dp[0] = 1
        for coin in coins:
            for j in range(coin, amount+1, 1):
                dp[j] += dp[j-coin]
        return dp[amount]

C++:

cpp 复制代码
class Solution {
public:
    int change(int amount, vector<int>& coins) {
        vector<int> dp(amount+1, 0);
        dp[0] = 1;
        for (int c : coins) {
            for (int j=c; j<=amount; j++) {
                dp[j] += dp[j-c];
            }
        }
        return dp[amount];
    }
};

377. 组合总和 Ⅳ

视频讲解:动态规划之完全背包,装满背包有几种方法?求排列数?| LeetCode:377.组合总和IV_哔哩哔哩_bilibili

代码随想录

Python:

python 复制代码
class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        dp = [0] * (target+1)
        dp[0] = 1
        for j in range(1, target+1):
            for num in nums:
                if num>j: continue
                dp[j] += dp[j-num]
        return dp[target]

C++:

C++要注意处理加法溢出的情况。

cpp 复制代码
class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target+1, 0);
        dp[0] = 1;
        for (int j=1; j<=target; j++) {
            for (int num:nums) {
                if (num > j || dp[j]>=INT_MAX-dp[j-num]) continue;
                dp[j] += dp[j-num];
            }
        }
        return dp[target];
    }
};
相关推荐
牛油果子哥q7 分钟前
【C++ STL string 】C++ STL string 终极精讲:底层原理、内存机制、全套API、深浅拷贝、易错坑点与工程实战规范
数据库·c++
KaMeidebaby7 分钟前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
Cloud_Shy6188 分钟前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 30 - 32)
开发语言·人工智能·笔记·python·学习方法
天佑木枫34 分钟前
15天Python入门系列 · 序
开发语言·python
happylifetree35 分钟前
Python017-第二章15.数据容器-dict常用操作
python
装不满的克莱因瓶1 小时前
了解 LangChain 中的 LLM 与 ChatModel 的差异
人工智能·python·ai·langchain·llm·agent·chatmodel
手写码匠1 小时前
从零实现 Prompt 工程引擎:结构化提示、自动优化与多轮自省体系
人工智能·深度学习·算法·aigc
无限码力1 小时前
阿里算法岗 0530笔试真题 - 多约束条件下的元素匹配统计
算法·阿里笔试真题·阿里机试真题·阿里算法岗笔试
lqqjuly1 小时前
MLA — 多头潜在注意力深度解析
深度学习·神经网络·算法
IT知识分享2 小时前
从零开发在线简繁转换工具:OpenCC 实战、避坑经验与方案选型
javascript·python