本文主要是介绍代码随想录-动态规划4(46. 携带研究材料(第六期模拟笔试) 、416. 分割等和子集),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
46. 携带研究材料(第六期模拟笔试)
#include <iostream>
#include <stdio.h>
#include <vector>using namespace std;int bag(int N, vector<int> &weight, vector<int> &value)
{int M = weight.size();vector<int> dp(N+1);for (int i=0; i<N+1; i++){dp[i] = weight[0]<=i ? value[0] : 0;}for (int i=1; i<M; i++){for (int j=N; j>0; j--){if (j-weight[i]>=0)dp[j] = max(dp[j], dp[j-weight[i]]+value[i]);}}return dp[N];}int main()
{int M;int N;for (int i=0; i<2; i++){if (i==0) cin >> M;if (i==1) cin >> N;}vector<int> weight(M);for (int i=0; i<M; i++){cin >> weight[i];}vector<int> value(M);for (int i=0; i<M;i++){cin >> value[i];}// cout << M << " " << N << endl;// cout << weight[0] << " " << weight[5] << endl;// cout << value[0] << " " << value[5] << endl;cout << bag(N, weight, value) << endl;}
416. 分割等和子集
class Solution {
public:bool canPartition(vector<int>& nums) {int target = 0;for (int i=0; i<nums.size(); i++){target += nums[i];}if (target%2 != 0) return false;vector<int> dp(target/2+1, 0);for (int i=0; i<nums.size(); i++){for (int j=target/2;j>0;j--){if (i==0) {if (j>=nums[i]) dp[j] = nums[i];}else{if (j-nums[i]<0) dp[j] = dp[j];else dp[j] = max(dp[j], dp[j-nums[i]]+nums[i]); }}}if (dp[target/2] != target/2) return false;return true;}
};
这篇关于代码随想录-动态规划4(46. 携带研究材料(第六期模拟笔试) 、416. 分割等和子集)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!