139.单词拆分
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp(s.size()+1, false);
dp[0]=true;
for(int i=1; i<=s.size(); i++){
for(int j=0;j<wordDict.size(); j++){
if(wordDict[j].size()>i) continue;
string word = s.substr(i-wordDict[j].size(), wordDict[j].size());
if(wordDict[j] == word && dp[i-wordDict[j].size()]==true){
dp[i] = true;
}
}
}
return dp[s.size()];
}
};
参考文章:代码随想录- 139.单词拆分
多重背包
#include<iostream>
#include<vector>
using namespace std;
int main(){
int C,N;
cin>>C>>N;
vector<int> weight(N,0), price(N,0), nums(N,0);
for(int i=0; i<N; i++) cin>>weight[i];
for(int i=0; i<N; i++) cin>>price[i];
for(int i=0; i<N; i++) cin>>nums[i];
vector<int> dp(C+1, 0);
for(int i=0; i<N; i++){
for(int j=C; j>=weight[i]; j--){
for(int k=1; k<=nums[i]&&k*weight[i]<=j; k++){
dp[j] = max(dp[j], dp[j-k*weight[i]]+k*price[i]);
}
}
}
std::cout << dp[C] << std::endl;
return 0;
}
参考文章:代码随想录-多重背包