Partition Equal Subset Sum
Given a non-empty array 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.
Note:
- Each of the array element will not exceed 100.
- The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.解析:
本题分解为看一个数组中是否存在某些元素的和为sum,动态规划dp[i]表示是否存在和为i的元素列,dp[j]=dp[j]||dp[j+nums[i]],从前向后遍历。
代码:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum=0;
for (int i=0; i<nums.size(); i++)
{
sum+=(nums[i]);
}
vector<bool>table(sum+1,false);
table[sum]=true;
int sum1=0;
if (sum%2||nums.size()<2) return false;
sum1=sum/2;
table[0]=true;
for (int i=0; i<nums.size(); i++)
{
for (int j=0; j<=sum; j++)
{
if ((j+nums[i])<=sum)
{
table[j]=table[j]||table[j+nums[i]];
}
}
}
return table[sum1];
}
};