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