Today, I came into contact with the knapsack problem. The first time I encountered it, I felt that it was not easy. The key to follow the steps is to determine the initialization and traversal of the array, and the recursive logic.
Problem 1: 416. Split Equal Sum Subsets - LeetCode
Idea: At the beginning, I thought about sorting them first and then using pointers to do it. It turned out that some test cases could not pass. From the reaction, this question is actually a knapsack problem. Find the subarray whose sum is sum/2 from the array. Yes, it's still a bit vague for recursive logic, the code is as follows:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum=0;
vector<int> dp(10001,0);
for(int i=0;i<nums.size();i++){
sum+=nums[i];
}
if(sum % 2 == 1) return false;
int target = sum/2;
for(int i=0;i<nums.size();i++){
for(int j=target;j>=nums[i];j--){
dp[j]=max(dp[j],dp[j-nums[i]]+nums[i]);
}
}
if(dp[target]==target) return true;
return false;
}
};