139. 单词拆分
dp[0]必须是True,后续要用到与运算,起始点必须是True
外循环必须是检查每个位置,因为后续有和自己的与运算,一定要在每个点检查所有可能性。
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dp = [False] * (len(s) + 1)
dp[0] = True
for j in range(1, len(s) + 1):
for word in wordDict:
if j >= len(word):
dp[j] = dp[j] or (dp[j - len(word)] and s[j - len(word):j] == word)
return dp[len(s)]
感觉参透了这两种背包!!!这题都AC了!!!啊哈哈哈哈!!!
卡码网第56题多重背包:
def MultiKnapsack(c, n, w, v, k):
new_w = []
new_v = []
# 按照二进制方法扩展物品列表
for i in range(n):
base = 1
while base <= k[i]:
new_w.append(w[i] * base)
new_v.append(v[i] * base)
k[i] -= base
base *= 2
if k[i] > 0:
new_w.append(w[i] * k[i])
new_v.append(v[i] * k[i])
# 使用新的物品列表更新m
m = len(new_w)
# 初始化dp数组
dp = [0] * (c + 1)
# 动态规划求解
for i in range(m):
for j in range(c, new_w[i] - 1, -1):
dp[j] = max(dp[j], dp[j - new_w[i]] + new_v[i])
return dp[c]
if __name__=='__main__':
c, n = map(int, input().strip().split())
w = list(map(int, input().strip().split()))
v = list(map(int, input().strip().split()))
k = list(map(int, input().strip().split()))
print(MultiKnapsack(c, n, w, v, k))
不知道为什么一直报潜在的数组越界。
然鹅换成C++就通过了。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int MultiKnapsack(int c, int n, vector<int>& w, vector<int>& v, vector<int>& k) {
vector<pair<int, int>> items;
for (int i = 0; i < n; ++i) {
int amount = k[i];
int base = 1;
while (amount > 0) {
int current = min(base, amount);
items.push_back(make_pair(w[i] * current, v[i] * current));
amount -= current;
base *= 2;
}
}
vector<int> dp(c + 1, 0);
for (auto& item : items) {
int weight = item.first;
int value = item.second;
for (int j = c; j >= weight; --j) {
dp[j] = max(dp[j], dp[j - weight] + value);
}
}
return dp[c];
}
int main() {
int c, n;
cin >> c >> n;
vector<int> w(n), v(n), 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];
}
cout << MultiKnapsack(c, n, w, v, k) << endl;
return 0;
}