代码随想录算法训练营第四十六天| 139.单词拆分、卡码网第56题
- 139.单词拆分
- 卡码网第56题
139.单词拆分
题目链接
文章讲解
class Solution {
public:bool wordBreak(string s, vector<string>& wordDict) {int bagSize = s.size(), n = wordDict.size();vector<bool> dp(bagSize + 1, false);dp[0] = true;for (int i = 1; i <= bagSize; i++) {for (int j = 0; j < n; j++) {int wordSize = wordDict[j].size();if (i < wordSize) continue;if (!dp[i - wordSize]) continue;string sub = s.substr(i - wordSize, wordSize);if (wordDict[j].compare(sub) == 0)dp[i] = true;}}return dp[bagSize];}
};
卡码网第56题
题目链接
文章讲解
#include<bits/stdc++.h>
using namespace std;
int c, n;
void slove() {vector<int> w(n);vector<int> v(n);vector<int> k(n);for (int i = 0; i < n; i++) cin >> w[i];for (int i = 0; i < n; i++) cin >> v[i];for (int i = 0; i < n; i++) cin >> k[i];// 定义dp数组并初始化vector<int> dp(c + 1, 0);// 遍历for (int i = 0; i < n; i++) {for (int j = c; j >= w[i]; j--) {for (int l = 1; l <= k[i] && (j - l * w[i]) >= 0; l++) {dp[j] = max(dp[j], dp[j - l * w[i]] + l * v[i]);}}}cout << dp[c] << endl;
}
int main() {while (cin >> c >> n) slove();return 0;
}