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.题目的意思是输入一个非空的、只含正整数的数组nums,要求咱们判断,数组nums可否被分红两个子数组,知足两个子数组的和相等。数组
例1:
输入: [1, 5, 11, 5]
输出: true
解释: 输入数组能够被分为[1, 5, 5]和[11].
例2:
输入: [1, 2, 3, 5]
输出: false
解释: 数组没法被拆分红两个和相等的子数组.code
public boolean canPartition(int[] nums) { int sum = 0; for(int num : nums){ sum += num; } if(sum % 2 != 0)return false; sum /= 2; boolean[] res = new boolean[sum+1]; int length = nums.length; res[0] = true; for(int i=1;i<=length;i++){ for(int j=sum;j>=nums[i-1];j--){ res[j] = res[j-nums[i-1]] || res[j]; } } return res[sum]; }