LeetCode刷题实战416:分割等和子集
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
示例
示例 1:
输入:nums = [1,5,11,5]
输出:true
解释:数组可以分割成 [1, 5, 5] 和 [11] 。
示例 2:
输入:nums = [1,2,3,5]
输出:false
解释:数组不能分割成两个元素和相等的子集。
解题
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0);
if(sum & 1)
return false;
int target = sum >> 1;
int size = nums.size();
bool dp[size+1][target+1];
memset(dp, 0, sizeof(bool)*(size+1)*(target+1));
for(int i=0; i<=size; ++i)
dp[i][0] = 1;
for(int i=1; i<size+1; ++i)
{
for(int j=0; j<target+1; ++j)
{
dp[i][j] = dp[i-1][j];
if (j >= nums[i-1])
dp[i][j] = dp[i][j] || dp[i-1][j-nums[i-1]];
}
}
return dp[size][target];
}
};