/**
Given a non-empty array nums 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.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 100
Related Topics数组 | 动态规划
👍 1535, 👎 0
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean canPartition(int[] nums) {
int target = 0;
for (int num : nums) {
target += num;
}
if (target % 2 == 1) {
return false;
}
target = target / 2;
boolean[][] dp = new boolean[nums.length + 1][target + 1];
dp[0][0] = true;
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (num > target) {
continue;
}
dp[i + 1][num] = true;
dp[i + 1][0] = true;
for (int j = 0; j <= target; j++) {
dp[i + 1][j] = dp[i][j];
if (!dp[i + 1][j] && j >= num) {
dp[i + 1][j] = dp[i][j - num];
}
}
}
return dp[nums.length][target];
}
}
//leetcode submit region end(Prohibit modification and deletion)