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.
题意:
给定一个数组,问该数组能否分成两个非空子集,使得这两个非空子集的元素之和相同
思路:
观察例1,sum=22, sum为偶数有可能partition两个子集
观察例2,sum=11,sum 为奇数不可能partition两个子集
这是一个背包问题,背包容量为数组中元素和的一半+1。这样只要看是否有元素正好填满背包即可。但每个元素只能用一次,所以在尝试放一个元素时还要避免对尝试放其他位置时对自己的影响。所以尝试放一个元素到背包的时候,要从容量最大的开始。
代码:
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for(int i = 0; i < nums.length; i++){
sum += nums[i];
}
if(sum % 2 != 0) return false; sum = sum / 2; int[]dp = new int[sum + 1];
dp[0] = 1;
for(int i = 0; i< nums.length; i++){
for(int j = sum; j>=nums[i]; j--){
dp[j] = dp[j]|dp[j-nums[i]];
}
}
return dp[sum] != 0;
}
}