一、题目描述
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,如果sum不能被2除断那么很明显无法分成两个和都相同的两组。如果能除断,那么就看数组中是否有和加起来等于sum/2 的组合了,用dp[i] 表示当前数组中加起来和等于i 的数的和。如果dp[sum/2] == sum/2,那么说明有组合加起来等于sum/2。
c++代码(312ms)
class Solution {
public:
bool canPartition(vector<int>& nums) {
int len=nums.size();
int sum=0;
for(int i=0; i<len; i++){
sum += nums[i];
}
if((sum%2)==1)
return false;
sum = sum/2;
vector<int> dp(sum+1, 0);
for(int i=0; i<len; i++){
for(int j=sum; j>=1; j--){
if(j>=nums[i]){
dp[j] = max(dp[j], nums[i]+dp[j-nums[i]]);
}
}
}
return dp[sum]==sum;
}
};