题目描述:
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.
将某个数组拆分一个子集,其和为数组之和的一半。可以先求出数组之和再求出子集之和,用动态规划判断是否能拆分出所求的子集。令dp[i]表示任选数组元素之和能否等于i,则依次遍历每个数组元素,对于j>=nums[i],如果dp[j-nums[i]]=true,那么dp[j]=true。
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum=0;
for(int i=0;i<nums.size();i++) sum+=nums[i];
if(sum%2==1) return false;
int target=sum/2;
vector<bool> dp(target+1,false);
dp[0]=true;
for(int i=0;i<nums.size();i++)
{
for(int j=target;j>=nums[i];j--)
{
if(dp[j-nums[i]]==true) dp[j]=true;
}
}
return dp[target];
}
};