416.分割等和子集
要点:把题意理解成容量为sum/2的背包问题,就可以套公式解决
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for (int i : nums)
sum += i;
int capacity = 0;
if (sum % 2 == 1)
return false;
else
capacity = sum / 2;
vector<int> dp(capacity + 1, 0);
for (int i = 0; i < nums.size(); i++) {
for (int j = capacity; j >= nums[i]; j--) {
dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]);
}
}
return dp[capacity] == capacity;
}
};