01背包问题 二维
46. 携带研究材料(第六期模拟笔试) (kamacoder.com)
#include<iostream>
#include<vector>
using namespace std;
int maxValue(const vector<int> &costs, const vector<int> &values, const int &n, const int &m)
{
vector<vector<int>> dp(m, vector<int>(n + 1));
for (int i = costs[0]; i <= n; i++)
{
dp[0][i] = values[0];
}
for (int i = 1; i < m; i++)
{
for (int j = 0; j <= n; j++)
{
if(j - costs[i] >= 0){
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - costs[i]] + values[i]);
}else{
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[m - 1][n];
}
int main(){
int M = 0, N = 0;
cin >> M >> N;
vector<int> costs(M);
vector<int> values(M);
for(int &cost : costs){
cin >> cost;
}
for(int &value : values){
cin >> value;
}
return maxValue(costs, values, N, M);
}
01背包问题 一维
416. 分割等和子集
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for(int num : nums){
sum += num;
}
if(nums.size() < 2){
return false;
}
if(sum % 2 != 0){
return false;
}
vector<int> dp(sum / 2 + 1, 0);
for(int i = 0; i < nums.size(); i++){
for(int j = sum / 2; j >= nums[i]; j--){
dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]);
}
}
return dp[sum / 2] == sum / 2;
}
};