代码随想录算法训练营第46天|139.单词拆分|关于多重背包,你该了解这些!|背包问题总结篇!
详细布置
关于 多重背包,力扣上没有相关的题目,所以今天大家的重点就是回顾一波 自己做的背包题目吧。
139.单词拆分
视频讲解:
https://www.bilibili.com/video/BV1pd4y147Rh
https://programmercarl.com/0139.%E5%8D%95%E8%AF%8D%E6%8B%86%E5%88%86.html
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string>wordset(wordDict.begin(),wordDict.end());
vector<bool>dp(s.size()+1,false);
dp[0]=true;
for(int i=1;i<=s.size();i++)
for(int j=0;j<i;j++)
{
string word=s.substr(j,i-j);
if(wordset.find(word)!=wordset.end()&&dp[j])
dp[i]=true;
}
return dp[s.size()];
}
};
关于多重背包,你该了解这些!
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
#include<iostream>
#include<vector>
using namespace std;
int main() {
int bagWeight,n;
cin >> bagWeight >> n;
vector<int> weight(n, 0);
vector<int> value(n, 0);
vector<int> nums(n, 0);
for (int i = 0; i < n; i++) cin >> weight[i];
for (int i = 0; i < n; i++) cin >> value[i];
for (int i = 0; i < n; i++) cin >> nums[i];
vector<int> dp(bagWeight + 1, 0);
for(int i = 0; i < n; i++) { // 遍历物品
for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量
// 以上为01背包,然后加一个遍历个数
for (int k = 1; k <= nums[i] && (j - k * weight[i]) >= 0; k++) { // 遍历个数
dp[j] = max(dp[j], dp[j - k * weight[i]] + k * value[i]);
}
}
}
cout << dp[bagWeight] << endl;
}
背包问题总结篇!
https://programmercarl.com/%E8%83%8C%E5%8C%85%E6%80%BB%E7%BB%93%E7%AF%87.html