https://leetcode.com/problems/partition-equal-subset-sum/description/
DP1.
bool canPartition(vector<int>& nums) {
int sm = accumulate(nums.begin(), nums.end(), 0);
if(sm&1) return false;
bitset<10001> bs(1);
for(int n: nums)
bs |= (bs<<n);
return bs[sm/2];
}
DP2.
bool canPartition(vector<int>& nums) {
int sm = accumulate(nums.begin(), nums.end(), 0);
if(sm & 1) return false;
vector<bool> dp(sm+1, false);
dp[0] = true;
for(auto n: nums) {
for(int i=dp.size()-1; i>=0; i--) {
if(dp[i]) dp[i+n] = true;
}
}
return dp[sm/2];
}
No comments:
Post a Comment