算法训练营day46

完全背包和01背包的区别就是是否可以重复使用,在代码上就是 j 的 for 循环从前向后遍历还是从后向前遍历

题目:52. 携带研究材料(第七期模拟笔试) (kamacoder.com)

复制代码
#include<iostream>
#include<vector>

using namespace std;

int main() {
    int N, V;
    cin >> N >> V;
    vector<int> wegiht(N, 0);
    vector<int> val(N, 0);
    for(int i = 0;i < N;i++) {
        cin >> wegiht[i] >> val[i];
    }
    vector<int> dp(V + 1, 0);
    for(int i = 0;i < N;i++) {
        for(int j = wegiht[i];j <= V;j++) {
            dp[j] = max(dp[j], dp[j - wegiht[i]] + val[i]);
        }
    }
    cout << dp[V] << endl;
    return 0;
}

题目2:518. 零钱兑换 II - 力扣(LeetCode)

先物品再背包是组合,先背包再物品是排列

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

题目3:377. 组合总和 Ⅳ - 力扣(LeetCode)

复制代码
class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<int> dp(target + 1, 0);
        dp[0] = 1;
        for(int j = 0;j <= target;j++) {
            for(int i = 0;i < nums.size();i++) {
                if (j - nums[i] >= 0 && dp[j] < INT_MAX - dp[j - nums[i]]) {
                    dp[j] += dp[j - nums[i]];
                }
            }
            for(int j = 0;j <= target;j++) {
                cout << dp[j] << ",";
            }
            cout << "---------" << endl;
        }
        return dp[target];
    }
};
相关推荐
月光船幽幽1 分钟前
四层公理框架驱动AI健康诊断
人工智能·python·科技·算法·安全
zmzb01035 分钟前
C++课后习题训练记录Day176
开发语言·c++
王维同学8 分钟前
跨位数进程的映像、命令行与环境块读取
c++·windows·安全
Rabitebla10 分钟前
C++ STL 之 set 详解:从底层红黑树到实际应用
开发语言·数据结构·c++·算法·leetcode
520拼好饭被践踏13 分钟前
JAVA+Agent学习day26
java·开发语言·数据结构·学习·agent
liulilittle20 分钟前
无锁多生产者多消费者队列的工程实现剖析——算法、内存模型与性能
算法·多线程·并发·无锁·mpmc·lock-free
郝学胜-神的一滴25 分钟前
力扣 692:巧用小顶堆高效求解前K个高频单词
java·数据结构·python·程序人生·算法·leetcode·职场和发展
科学实验家35 分钟前
贪心算法:分饼干
算法·贪心算法
誰能久伴不乏39 分钟前
深入解析 C++ STL 底层原理:从设计哲学到内存收割机
c++·架构·stl
额,不知道写啥。1 小时前
题解:P16710 愿望
数据结构·算法