給定一個只包含正整數的非空數組。是否可以將這個數組分割成兩個子集,使得兩個子集的元素和相等。
注意:
- 每個數組中的元素不會超過 100
- 數組的大小不會超過 200
示例 1:
輸入: [1, 5, 11, 5] 輸出: true 解釋: 數組可以分割成 [1, 5, 5] 和 [11].
示例 2:
輸入: [1, 2, 3, 5] 輸出: false 解釋: 數組不能分割成兩個元素和相等的子集.
class Solution {
public boolean canPartition(int[] nums) {
if(nums == null) return false;
if(nums.length >200) return false;
int total =0;
for(int i=0; i< nums.length; i++){
if(nums[i] > 100)
return false;
total += nums[i];
}
if(total % 2 != 0) return false;
int avg = total /2;
boolean[] arr = new boolean[total +1];
arr[0] = true;
for(int n: nums){
for(int i = avg; i>= n; i--){
arr[i] = arr[i] || arr[i-n];
}
}
return arr[avg];
}
}