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].
给出一个数组,问能不能把数组分割成两个子集,使每个子集的和为数组全部元素和的一半。
数组元素都是正整数。
思路:
因为元素都是正整数,所以子集的和也是正整数,意味着原整个数组的和(子集的和 * 2)应该是偶数。
因此原数组的和为奇数时直接返回false.
假设原数组元素的和是sum,定义长度为sum+1的DP数组,表示数组中选取元素能不能构成sum的和,也就是来了一个元素,把它和上一步所有可能的和相加,得到新的所有可能的和。
为了节省space空间,把二维DP数组压缩到一维,从右往左访问DP数组,这样就不至于重复访问数组中的元素。
每次遍历一遍DP,看sum/2处是否为true,为true时直接返回。
public boolean canPartition(int[] nums) {
if(nums == null || nums.length == 0) {
return false;
}
int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
}
if(sum % 2 == 1) {
return false;
}
boolean[] dp = new boolean[sum + 1];
dp[0] = true;
for(int num : nums) {
for(int i = sum; i >= 0; i--) {
if(dp[i]) {
dp[i + num] = true;
}
}
if(dp[sum/2]) {
return true;
}
}
return false;
}
394

被折叠的 条评论
为什么被折叠?



